Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 482
Charles Yeung Avatar asked Mar 22 '11 08:03

Charles Yeung


People also ask

How do I check if a string contains a specific word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you check if a string contains a specific character in JavaScript?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do I check if a string contains text?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you check if a variable contains a string in jQuery?

You can check using Javascript . IndexOf() if a string contains substring or not, it returns Index of substring if it is in a string otherwise it returns 0. console.


1 Answers

you can use indexOf for this

var a = 'how are you'; if (a.indexOf('are') > -1) {   return true; } else {   return false; } 

Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,

var a = 'how are you'; return a.indexOf('are') > -1; 

Update in ECMAScript2016:

var a = 'how are you'; return a.includes('are');  //true 
like image 110
naiquevin Avatar answered Sep 21 '22 04:09

naiquevin