Javascript string search: The Complete Guide

1
14
String Search() Method in Javascript

The search() method searches the string for the specified value and returns its position of the match.

Javascript string search()

Javascript String search() is a built-in function that executes the search for a match between a regular expression and this String object. The search value can be the string or regular expression. The search method returns -1 if no match is found.

Syntax

The syntax of the JavaScript string search() method is the following.

string.search(searchvalue)

Parameters

The searchValue parameter is required, and it is a regular expression.  The string will automatically be converted to the regular expression. The method returns a Number, representing the position of the first occurrence of the specified searchValue, or -1 if no match is found.

Example

// app.js

let str = 'Obama was US president';
let result  = str.search('was');
console.log(result);

Javascript String Search Example | String.prototype.search()

So, in the above example, it searches for was substring and if found then it will return the index of that string. In our case, its position is 6, so it returns the 6.

The argument of the search() method is a regular expression object. If the non-RegExp object is passed, it is implicitly converted to a RegExp by using a new RegExp().

When you want to know whether the pattern is found and also its index in the string then use the search() method.

// app.js

let str = 'Jude Law';
let result1 = /[A-Z]/g;
var result2 = /[.]/g;
console.log(str.search(result1));
console.log(str.search(result2));

String.prototype.search()

That’s it for this tutorial.

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.