JavaScript String Search Tips & Tricks
Here are a few JavaScript string search tips along with examples:
Using the indexOf() method:
The indexOf() method returns the index of the first occurrence of a specified string within another string. If the specified string is not found, it returns -1.
Example:
const str = "JavaScript is awesome!";
const searchStr = "awesome";
const index = str.indexOf(searchStr);
if (index !== -1) {
console.log(`"${searchStr}" found at index ${index}`);
} else {
console.log(`"${searchStr}" not found`);
}
Output: “awesome” found at index 13
Using the includes() method:
The includes() method checks whether a string contains a specified string or not. It returns true if the string is found, otherwise false.
Example:
const str = "JavaScript is awesome!";
const searchStr = "awesome";
const isFound = str.includes(searchStr);
if (isFound) {
console.log(`"${searchStr}" found`);
} else {
console.log(`"${searchStr}" not found`);
}
Output: “awesome” found
Using regular expressions:
Regular expressions provide powerful search capabilities in JavaScript. You can use the test() method of a regular expression object to check whether a string matches the pattern or not.
Example:
const str = "JavaScript is awesome!";
const searchStr = /is\s\w+/;
const isMatched = searchStr.test(str);
if (isMatched) {
console.log(`"${searchStr}" matched`);
} else {
console.log(`"${searchStr}" not matched`);
}
Output: “/is\s\w+/” matched
These are just a few examples of how you can search for strings in JavaScript. There are many other methods and techniques available depending on your specific needs.