How do you check whether a string contains something?
Use the includes() method for a yes-or-no answer, and use indexOf() when you also need the position. These newer string methods were added in the 2015 edition of the language precisely so that you would not have to write indexOf() and compare the result to minus one every single time.
const url = 'https://example.com/docs/guide';
console.log(url.includes('docs')); // true
console.log(url.startsWith('https://')); // true
console.log(url.endsWith('guide')); // true
console.log(url.indexOf('docs')); // 20
console.log(url.indexOf('missing')); // -1
// A small guard function built on startsWith.
function isSecure(address) {
return address.startsWith('https://');
}
console.log(isSecure(url)); // true
console.log(isSecure('http://example.com')); // false
The startsWith() and endsWith() methods take a position as an optional second argument. That position tells the method where to start looking or where to stop looking. It is useful when you have a string and you want to check the end of it while ignoring a trailing newline or a suffix that the platform added for you.
There is one trap that is worth knowing. The includes() and startsWith() methods reject a regular expression, so passing a pattern to them throws a TypeError. If you need pattern matching, use the search() method or the match() method, or build a regular expression and test that instead.
For case-insensitive checks, convert both sides to the same case first, or use the regular expression flag that ignores case. Just remember that lowercasing the whole string creates a new string in memory, so on a very hot path a regular expression with the flag is often the cheaper choice.