$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?
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With