In JavaScript, you can check whether a string contains a substring using several methods. Here are some common approaches:
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');
}
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');
}
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');
}
Work with our skilled Javascript developers to accelerate your project and boost its performance.
Hire JavaScript Developers