How do you check whether a string contains something?
Use the includes method for a yes or no answer, and indexOf when you need the position. The newer string methods were added in the 2015 edition precisely so that you would not have to write indexOf and compare the result to minus one every 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.
const isSecure = (u) => u.startsWith("https://");
console.log(isSecure(url)); // true
console.log(isSecure("http://example.com")); // falseThe startsWith and endsWith methods take a position as an optional second argument, which tells the method where to start or where to stop looking. That is useful when you have a string and you want to check the end of it but ignore a trailing newline or a suffix that the platform added.
One trap worth knowing. The includes and startsWith methods reject a regular expression, so passing a pattern throws a TypeError. If you need pattern matching, use the search method or the match method, or construct 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 allocates a new string, so on a very hot path a regular expression with the flag is often cheaper.