JavaScript String search() method

The search() method in JavaScript is used to search a string for a specified regular expression, and return the position of the match within the string. This method takes a single argument, which is the regular expression to search for in the string. If the regular expression is found, the search() method returns the index at which the match was found. If the regular expression is not found, the search() method returns -1.

Here is an example of how the search() method works:

const string1 = 'Hello, world!';
const regex1 = /world/gi;

const result = string1.search(regex1);

// the result will be: 7

In the code example above, we first declare a string called string1 that contains the text Hello, world!. We also declare a regular expression called regex1 that matches the substring world. We then use the search() method to search the string1 string for the regex1 regular expression. The search() method takes a single argument, which is the regular expression to search for in the string. In this case, we pass in the regex1 regular expression as the argument to the search() method.

As a result of calling the search() method, the result variable will be set to 7, which is the index at which the regex1 regular expression was found in the string1 string. If the string1 string did not contain the regex1 regular expression, the result variable would be set to -1.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: