Home >Web Front-end >JS Tutorial >How Can I Check if a String Contains a Substring in JavaScript?

How Can I Check if a String Contains a Substring in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 20:42:10541browse

How Can I Check if a String Contains a Substring in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn