Analyzing Text
Modern JS allows you to easily search for text parts inside a string without complex regular expressions.
1. Modern Methods (True/False)
str.includes(substr): Was a match found?str.startsWith(substr): Does the string start with this?str.endsWith(substr): Does it end with this?
2. Good Old indexOf
Returns the POSITION (index) of the first match or -1 if nothing is found.
let str = "Moo";
alert( str.indexOf("oo") ); // 1 (0-based indexing: M=0, o=1, o=2)
Caution
Case matters! Searching for includes("Widget") will not find the word "widget". Always coerce to the same case before searching if exact matching isn't critical.
Tip
All these methods have a second argument — the starting position for the search. For example, str.includes("a", 5) will start searching for " a " only from the 5th character.