2

How to use match javascript for search specific word ?

By this code I want to alert not found

function check() {
  var str = "abcdefg";
  if (str.match(/abc/)) {
    alert("found");
  } else {
    alert("not found");
  }
}
<div onclick="check()">CLICK HERE</div>

And for this code I want to alert found

function check() {
  var str = "abc";
  if (str.match(/abc/)) {
    alert("found");
  } else {
    alert("not found");
  }
}
<div onclick="check()">CLICK HERE</div>

How can I do this?

mplungjan
  • 169,008
  • 28
  • 173
  • 236

1 Answers1

2

Use RegExp#test method for searching a match and use word boundary regex for exact word match.

<div onclick="check()">CLICK HERE</div>

<script>
  function check() {
    var str = "abcdefg";
    if (/\babc\b/.test(str)) {
      alert("found");
    } else {
      alert("not found");
    }
  }
</script>

UPDATE : If you want to generate regex from a string then use RegExp constructor.

<div onclick="check()">CLICK HERE</div>

<script>
  function check() {
    var str = "abcdefg",
      check = "abc";
    if (new RegExp('\\b' + check + '\\b').test(str)) {
      alert("found");
    } else {
      alert("not found");
    }
  }
</script>

Refer : Converting user input string to regular expression

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188