AppDividend
Latest Code Tutorials

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

1 51

Get real time updates directly on you device, subscribe now.

Javascript String Search Example | String.prototype.search() is today’s topic. The javascript string search() method executes the search for a match between a regular expression and this String object. The string search() method searches the string for the specified value and returns its position of the match. The search value can be the string or the regular expression. The search method returns -1 if no match is found.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript String Search Example

The syntax for js string search method is following.

string.search(searchvalue)

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 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, Javascript String Search Example | String.prototype.search() 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.