JavaScript String Search Tips & Tricks

Rahul Kaklotar
2 min readApr 6, 2023

--

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

JavaScript String Search Tips & Tricks

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

JavaScript String Search Tips & Tricks

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.

--

--

Rahul Kaklotar

I'm front-end developer with 4 years of expertise in HTML, CSS, JavaScript, React. Passionate about creating user-friendly websites with a sharp eye for detail.