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
Release: 2024-12-19 20:42:10
Original
526 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template