Kaiusee
Kaiusee

Reputation: 55

What is the algorithm of the search() function?

Does any body know what the algorithm used for the search() function in javascript is?

var myRegExp = /Alex/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);

if(matchPos1 != -1)
    document.write("There was a match at position " + matchPos1); 
else
    document.write("There was no match in the first string");

Example copied tizaq.com

I need to use this function to search a text document for different string values. But I need to document what the algorithm behind this method is, and what the complexity is. Otherwise I have to write my own method that searches the text file that I have.

Upvotes: 2

Views: 155

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

The specification says it's implemented as a regular expression match:

3) If Type(regexp) is Object and the value of the [[Class]] internal property of regexp is "RegExp", then let rx be regexp;

4) Else, let rx be a new RegExp object created as if by the expression new RegExp( regexp) where RegExp is the standard built-in constructor with that name.

5) Search the value string from its beginning for an occurrence of the regular expression pattern rx. Let result be a Number indicating the offset within string where the pattern matched, or –1 if there was no match. (...)

(Section 15.5.4.12 String.prototype.search (regexp)).

This means your question boils down to the regex matching algorithm. But that is not in the specification either, it depends on the implementation:

The value of the [[Match]] internal property is an implementation dependent representation of the Pattern of the RegExp object.

(Section 15.10.7 Properties of RegExp Instances).

So, if documenting the complexity of that algorithm is really a requirement, I guess you'll have to write your own method. But keep in mind that, by doing that, you'll probably come up with something less efficient, and probably dependent on other built-in methods whose complexity is unknown (maybe even RegExp itself). So, can't you convince the powers that be that documenting the complexity of a built-in, implementation-dependent js method is not your job?

Upvotes: 1

Related Questions