AppDividend
Latest Code Tutorials

Javascript String Search: How to Search String in JavaScript

The search() method searches the string for the specified value and returns its position of the match. The search value can be the string or regular expression. The search method returns -1 if no match is found.

Javascript string search()

Javascript String search() is an inbuilt function that executes the search for a match between a regular expression and this String object.

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.

// 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()

Finally, the Javascript String search() example is over.

1 Comment
  1. ravish yadav says

    Nice article

Leave A Reply

Your email address will not be published.

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