In JavaScript, you can check whether a string contains a substring using several methods. Here are some common approaches:

1. Using indexOf() method

The indexOf() method returns the index within the string of the first occurrence of the specified substring, or -1 if the substring is not found.

Example:

const str = 'Hello, world!';
const substring = 'world';

if (str.indexOf(substring) !== -1) {
 console.log('Substring found');
} else {
 console.log('Substring not found');
}

2. Using includes() method

The includes() method determines whether a string contains the specified substring. It returns true if the substring is found, otherwise false.

Example:

const str = 'Hello, world!';
const substring = 'world';

if (str.includes(substring)) {
 console.log('Substring found');
} else {
 console.log('Substring not found');
}

3. Using Regular Expressions (RegExp)

You can also use regular expressions to check for substrings within a string.

Example:

const str = 'Hello, world!';
const substring = 'world';
const regex = new RegExp(substring);

if (regex.test(str)) {
 console.log('Substring found');
} else {
 console.log('Substring not found');
}

Support On Demand!

JavaScript