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

How Can I Check for a Substring in a JavaScript String?

Mary-Kate Olsen
Release: 2024-12-30 05:11:18
Original
717 people have browsed it

How Can I Check for a Substring in a JavaScript String?

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.");
}
Copy after login

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

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.");
}
Copy after login

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!

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