Alvin
Alvin

Reputation: 8499

regex return whole word match result

How do I match whole word?

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a global search for "is" in a strisng.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Is Alvin this all there is sis?";
    var patt1 = /is|alvin/gi;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
}
</script>

</body>
</html>

Upvotes: 0

Views: 133

Answers (1)

Barmar
Barmar

Reputation: 780861

Use the \b word boundary pattern.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a global search for "is" in a strisng.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Is Alvin this all there is sis?";
    var patt1 = /\b(?:is|alvin)\b/gi;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
}
</script>

</body>
</html>

Upvotes: 1

Related Questions