Javascript string search: The Complete Guide

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.


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


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  ='was');

Javascript String Search Example |

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;

That’s it for this tutorial.

1 thought on “Javascript string search: The Complete Guide”

Leave a Comment

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