Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript String search()

The search() method scans a string for a specified string or regular expression and yields the position of the match.

Example

let text = “Please locate where ‘locate’ occurs!”;
text.search(“locate”);
let text = “Please locate where ‘locate’ occurs!”;
text.search(/locate/);

Did You Notice?

Are the two methods, indexOf() and search()equivalent?

Do they accept the same arguments (parameters) and return the same value?

While indexOf() and search() methods share some similarities, they are not identical. Here are the differences:

  1. The search() method does not accept a second start position argument.
  2. The indexOf() method cannot handle advanced search values like regular expressions.
  3. Further details on regular expressions will be covered in a subsequent chapter.
  4. JavaScript String match()
  5. The match() method retrieves an array containing the outcomes of matching a string against another string or a regular expression.
  6. Example
  7. Conduct a search for “ain”.

let text = “The rain in SPAIN stays mainly in the plain”;

text.match(“ain”);

Execute a search for “ain”.

let text = “The rain in SPAIN stays mainly in the plain”
text.match(/ain/);

Execute a global search for “ain”.

let text = “The rain in SPAIN stays mainly in the plain”
text.match(/ain/g);

Conduct a case-insensitive global search for “ain”.

let text = “The rain in SPAIN stays mainly in the plain”
text.match(/ain/gi);

Note

If a regular expression lacks the g modifier (indicating a global search), match() will solely return the first match found in the string.