How to check whether a string contains a substring in JavaScript?
In JavaScript, you have numerous options for determining whether a string contains a substring. Here are a few of the most prevalent approaches:
String.prototype.includes():
The includes() method determines whether a string contains a given substring and returns a boolean value (true or false).
const str = 'Hello, world!';
const substring = 'world';
if (str.includes(substring)) {
console.log('Substring found.');
} else {
console.log('Substring not found.');
}
String.prototype.indexOf():
The indexOf() method returns the first index in the string at which a substring can be found. If the substring cannot be retrieved, the function returns -1.
const str = 'Hello, world!';
const substring = 'world';
if (str.indexOf(substring) !== -1) {
console.log('Substring found at index ' + str.indexOf(substring));
} else {
console.log('Substring not found.');
}
String.prototype.search():
The search() method searches the string for a regular expression pattern and returns the index of the first match or -1 if none are found.
const str = 'Hello, world!';
const regex = /world/;
if (str.search(regex) !== -1) {
console.log('Substring found at index ' + str.search(regex));
} else {
console.log('Substring not found.');
}
Regular Expressions:
Regular expressions can also be used to find substrings in a string. Regular expressions offer greater versatility, allowing you to match patterns and conduct more complicated searches.
const str = 'Hello, world!';
const regex = /world/;
if (regex.test(str)) {
console.log('Substring found using regular expression.');
} else {
console.log('Substring not found.');
}
Practice More on: https://interviewplus.ai/developers-and-programmers/javascript/questions
Comments
Post a Comment