Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains word (not substring)

Tags:

javascript

I am trying to check if a string contains a particular word, not just a substring.

Here are some sample inputs/outputs:

var str = "This is a cool area!";
containsWord(str, "is"); // return true
containsWord(str, "are"); // return false
containsWord(str, "area"); // return true

The following function will not work as it will also return true for the second case:

function containsWord(haystack, needle) {
     return haystack.indexOf(needle) > -1;
}

This also wouldn't work as it returns false for the third case:

function containsWord(haystack, needle) {
     return (' ' +haystack+ ' ').indexOf(' ' +needle+ ' ') > -1;
}

How do I check if a string contains a word then?

like image 516
chris97ong Avatar asked Feb 04 '26 07:02

chris97ong


2 Answers

Try using regex for that, where the \b metacharacter is used to find a match at the beginning or end of a word.

var str = "This is a cool area!";

function containsWord(str, word) {
  return str.match(new RegExp("\\b" + word + "\\b")) != null;
}

console.info(containsWord(str, "is")); // return true
console.info(containsWord(str, "are")); // return false
console.info(containsWord(str, "area")); // return true
like image 180
xxxmatko Avatar answered Feb 05 '26 19:02

xxxmatko


You can remove all special characters and then split string with space to get list of words. Now just check id searchValue is in this word list

function containsWord(str, searchValue){
  str = str.replace(/[^a-z0-9 ]/gi, '');
  var words = str.split(/ /g);
  return words.indexOf(searchValue) > -1
}

var str = "This is a cool area!";
console.log(containsWord(str, "is")); // return true
console.log(containsWord(str, "are")); // return false
console.log(containsWord(str, "area")); // return true
like image 20
Rajesh Avatar answered Feb 05 '26 21:02

Rajesh