Checking for Substring Presence in a JavaScript String
Despite the absence of an explicit String.contains() method in JavaScript, there are various approaches to determine if a string includes a specific substring.
One widely-used method is the String.indexOf() function. This function returns the index of the first occurrence of a specified substring within a string. If the substring is not found, it returns -1.
const string = "Hello world!"; const substring = "world"; const index = string.indexOf(substring); if (index !== -1) { console.log("Substring found!"); } else { console.log("Substring not found."); }
ES6 introduced the String.prototype.includes() method, providing a more concise syntax for this check. It returns a boolean value indicating whether the string includes the specified substring.
const string = "Hello world!"; const substring = "world"; console.log(string.includes(substring)); // true
Using regular expressions is another option. The String.match() method takes a regular expression as an argument and returns an array of matches. If the substring is found, the resulting array will have a length greater than 0.
const string = "Hello world!"; const substring = "world"; const regex = new RegExp(substring); const matches = string.match(regex); if (matches && matches.length > 0) { console.log("Substring found!"); } else { console.log("Substring not found."); }
The above is the detailed content of How Can I Check for a Substring in a JavaScript String?. For more information, please follow other related articles on the PHP Chinese website!