Finding Substrings in JavaScript
Many programming languages provide a straightforward method for checking whether a string contains a particular substring. However, despite expectations, the JavaScript language does not have a dedicated String.contains() method.
Finding a Solution
For JavaScript developers, there are several alternatives for detecting substrings:
String.prototype.includes (ES6 ):
Introduced in ECMAScript 6, this method returns a boolean indicating whether the string contains the specified substring.
const string = "foo"; const substring = "oo"; console.log(string.includes(substring)); // true
String.prototype.indexOf:
This method returns the first index of the substring within the string, or -1 if it's not found. You can check if the index is greater than or equal to 0 to determine the substring's existence.
const string = "foo"; const substring = "oo"; const index = string.indexOf(substring); console.log(index !== -1); // true
String.prototype.search:
Similar to indexOf, but performs a regular expression search. It returns the first matching index or -1 if not found. However, since substrings are not regular expressions by default, you'll need to prefix the substring with .
const string = "foo"; const substring = "oo"; const index = string.search(`\${substring}`); console.log(index !== -1); // true
String.prototype.match:
This method returns an array of matches found within the string. If the array has at least one item, the substring exists.
const string = "foo"; const substring = "oo"; const matches = string.match(substring); console.log(matches.length > 0); // true
Conclusion:
While JavaScript doesn't have a dedicated contains method, developers have several viable options for checking substrings, each with its own performance characteristics and suitability for specific use cases.
The above is the detailed content of How Can I Efficiently Check for Substrings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!