Wednesday 21 August 2019

JavaScript/jQuery - How to check if a string contain specific words



$a = 'how are you';

if (strpos($a,'are') !== false) {
echo 'true';
}


In PHP, we can use the code above to check if a string contain specific words, but how can I do the same function in JavaScript/jQuery?


Answer



If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:



/\bare\b/gi


\b = word boundary
g = global
i = case insensitive (if needed)


If you just want to find the characters "are", then use indexOf.



If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...