JavaScript String search() Tutorial

In this section, we will learn what the search() element is in JavaScript and how to use it.

JavaScript Find in String: search() Method

The string search() method in JavaScript helps us to search for a value in a string text.

Basically, this method accepts a value (a string value) and starts to look in the target string for that value to see if it can find one or not.

JavaScript String search() Syntax

string.search(searchvalue)

String search() Method Parameters:

The string search() method takes only one argument, and that is a regular expression, which is basically the value (or the pattern of the value) we want to search for it in the target string.

Note: if we pass a string value as the argument to this method, it will be converted into the regular expression automatically.

String search() Method Return Value:

The return value of this method is the position (index number) of the first occurrence of the sub-value.

If the value couldn’t be found in the target string, the return value will be -1.

Example: JavaScript search string

function func(...name){
  console.log(name);
}
const name = "John Doe John Doe John Doe John Doe";
const res = name.search("Doe");
console.log(res);

Output: 5

Leave a Reply