简体   繁体   中英

Check if string contains word (not substring)

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?

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 

 $(function(){ function containsWord(haystack, needle) { return haystack.replace(/[^a-zA-Z0-9 ]/gi, '').split(" ").indexOf(needle) > -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")); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM