JavaScript string.search() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript string.search() Method
  2. Example Code: Use the regExp Parameter Value for the string.search() Method
  3. Example Code: Use Lowercase or Uppercase Parameter Value for the string.search() Method
JavaScript string.search() Method

The string.search() method takes the regular expression and finds the first match from the index position in the JavaScript string.

Syntax of JavaScript string.search() Method

referenceString.search(searchValue);

Parameters

searchValue To search the value in the given string from the index position.

Return

It returns the index of the first match from the given string and returns -1 if any match is not found.

Example Code: Use the regExp Parameter Value for the string.search() Method

let referenceString = "Hello World! Welcome to Coding";
let regExp = 'Welcome';
let searchString = referenceString.search(regExp);
console.log(searchString);

Output:

13

The JavaScript string.search() method uses the regular expression as a parameter and returns the first match in the string.

Example Code: Use Lowercase or Uppercase Parameter Value for the string.search() Method

let string = "Repeating the words Code and code.";
let strWord = /code/;
let searchString = string.search(strWord);
console.log(searchString);

Output:

29

The string.search() method is case-sensitive and returns the index position of the word with an exact match. We’ve searched for the first occurrence of the lowercase word in the string by passing the lowercase searchValue.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript API