+ 16

How do I check if a string contains a substring in Javascript?

JS check for substring within a string

17th Oct 2018, 12:31 PM
Sonic
Sonic - avatar
4 Antworten
+ 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
17th Oct 2018, 12:38 PM
TurtleShell
TurtleShell - avatar
+ 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
17th Oct 2018, 1:17 PM
KrOW
KrOW - avatar
+ 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
19th Oct 2018, 3:53 AM
David Carroll
David Carroll - avatar
+ 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
19th Oct 2018, 10:02 PM
Sergei No
Sergei No - avatar