JavaScript String Search Methods

JavaScript String Search Methods

JavaScript provides several methods that search strings: indexOf, lastIndexOf, and search.
These basic methods tell you whether a match has been found.
The first three return the location in the string of the match, or -1 if no match is found.

JavaScript String search() Method

The search() method searches a string for a specified value, and returns the position of the match.
This method accepts single parameter A which holds the regular expression as object.
The string.search() method is the inbuilt method in JavaScript which is used to search for a match in between regular expressions and a given string object.
This method returns -1 if no match is found.
The search value can be string or a regular expression.

Syntax:
string.search(searchvalue)

searchvalue : Required. A regular expression.
A string will automatically be converted to a regular expression.

Example: #1

Perform a case-sensitive search:

var str = “Mr. Joshi has a new house”;
var n = str.search(“Joshi”);

// It will Return 4

Example: #2

Perform a case-insensitive search:

var str = “Mr. Joshi has a new house”;
var n = str.search(/joshi/i);

// It will Return 4

f you have any query or suggestions, feel free to ask me via the comment section below.

Leave a Reply