Checking for Substrings in Strings: Exploring JavaScript Methods
In JavaScript, the absence of a dedicated String.contains() method can raise questions about how to effectively determine whether one string contains another. Let's delve into a practical solution.
Method: String.prototype.includes
Modern JavaScript (ECMAScript 6 onwards) offers a clean and straightforward method for checking substrings: String.prototype.includes. This method takes a target substring as an argument and returns a Boolean value:
const string = "foo"; const substring = "oo"; console.log(string.includes(substring)); // true
The output will be "true" because the substring "oo" is contained within the string "foo". This method is efficient and provides a clear indication of substring presence.
The above is the detailed content of How Can I Check if a String Contains a Substring in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!