+ 16
How do I check if a string contains a substring in Javascript?
JS check for substring within a string
4 Réponses
+ 7
JS strings have an includes() method which checks for a substring (and is case sensitive) e.g.
"hello world".includes("world"); // true
"abcdef".includes("ac"); // false
There's an optional 2nd parameter that tells the method character position to start from
+ 7
... or using .indexOf method that return at which index found substring (-1 if not found).
P.S. .indexOf is more supported if you need of more compatibility
+ 5
If you need more flexibility with finding a pattern within a string, you can use String.match() function.
e.g. Searching for matches containing "hello" or "hallo":
"hello world".match(/(h[ae]llo)/) != null; //true
"hallo world".match(/(h[ae]llo)/) != null; //true
"hollo world".match(/(h[ae]llo)/) != null; //false
+ 5
At least couple of methods:
1. "string".includes(another);
2. "string".indexOf(another) > -1;
3. "string".lastIndexOf(another) > -1;
4. "string".split(another).length > 1;
5. "string".match(another);
6. "string".search(another) > -1;
Enjoy