Javascript String search()

Introduction

Javascript search() method finds patterns.

str.search(regexp)
  • regexp - a regular expression object.

The only argument for this method is a regular expression specified by either a string or a RegExp object.

The search() method returns the index of the first pattern occurrence in the string or -1 if not found.

The search() starts the search at the beginning.

let text = "cat, bat, sat, fat";     
let pos = text.search(/at/); 
console.log(pos);  // 1 

Here, search(/at/) returns 1, which is the first position of "at" in the string.

let str = "TEST css"
let re = /[A-Z]/g
let re2 = /[.]/g/*from w w  w  . ja  v  a  2s.c om*/
console.log(str.search(re)); 
console.log(str.search(re2));



PreviousNext

Related