search()  String  instance method JS Home  <<  JS Reference  <<  String  <<  search()

Description

Tries to locate a match between a regular expression and this String object.

  • If a match is located returns the index of the regular expression.
  • If no match is located -1 is returned.
  • When you wish to know if a pattern is found in a string use the search() method.
    Similar to the regular expression RegExp.test() method.
  • You get more information at the cost of speed by using the match() method.
    Similar to the regular expression RegExp.exec() method.

Syntax

Signature Description
aString.search(regexp)Tries to locate a match between a regular expression and this String object.

Parameters

Parameter Description
regexpA regular expression or RegExp object.
  • The object passed is implicitly converted to a RegExp object if it isn't already.

Examples

The code below searches for numerics in a string and returns the index position of the first found.


// Create a string variable.
var aStringToSearch = 'The children had 12 toys';

// Search for numerics.
alert(aStringToSearch.search(/\d+/));

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 8 - Strings