How to make a search for text in JavaScript

Learn how to create a text search in JavaScript with an example! Discover how to use regular expressions and string methods to search, find and replace strings.

Search for Text in JavaScript

Searching for text in JavaScript can be done in multiple ways. One of the most popular methods is using the String.prototype.search() method. This method returns the index of the first occurrence of the search string, or -1 if the search string is not present in the string.

For example, if we want to search for the string "text" in the string "Example of text search", we can use the String.prototype.search() method like this:


let exampleString = "Example of text search";
let searchString = "text";

let searchResult = exampleString.search(searchString);
// searchResult = 11

In this example, searchResult is 11 because the index of the first occurrence of the search string "text" is 11. If the search string is not present in the string, the method will return -1. For example, if we search for "xyz" in the same string:


let exampleString = "Example of text search";
let searchString = "xyz";

let searchResult = exampleString.search(searchString);
// searchResult = -1

In this example, searchResult is -1 because the search string is not present in the string.

Another popular method for searching for text in JavaScript is using the String.prototype.indexOf() method. This method is similar to String.prototype.search(), but it only returns the index of the first occurrence of the search string. For example, if we want to search for the string "text" in the string "Example of text search", we can use the String.prototype.indexOf() method like this:


let exampleString = "Example of text search";
let searchString = "text";

let searchResult = exampleString.indexOf(searchString);
// searchResult = 11

In this example, searchResult is 11 because the index of the first occurrence of the search string "text" is 11. If the search string is not present in the string, the method will return -1. For example, if we search for "xyz" in the same string:


let exampleString = "Example of text search";
let searchString = "xyz";

let searchResult = exampleString.indexOf(searchString);
// searchResult = -1

In this example, searchResult is -1 because the search string is not present in the string.

These are just two of the many methods available for searching for text in JavaScript. Depending on your use case, there may be other methods that are more suitable for your needs.

Answers (0)