skeggse
skeggse

Reputation: 6323

Why does the argument to string.search behave like a Regex?

I don't know about other Javascript engines, but in V8, including Chrome and Node.js, String.prototype.search behaves in an unexpected fashion.

> "054".search("0.4")
0 // expected -1
> "Sample String 007".search("0.7")
14 // expected -1
> "Sample String 0.7".search("0.7")
14 // expected behavior

If this is the expected behavior, why is that the case? And if this is the expected behavior, how do I properly search for a String without regular expressions coming in to play?

Upvotes: 6

Views: 2027

Answers (1)

apsillers
apsillers

Reputation: 115940

MDN's page on String.search has this to say about the function's argument:

If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

Therefore, the strings in your examples are correctly coerced into a regular expression objects. Your tests are equivalent to:

"054".search(new RegExp("0.4"))
"Sample String 007".search(new RegExp("0.7"))
"Sample String 0.7".search(new RegExp("0.7"))

and they return the correct result.

As @meetamit notes for your second question, you actually want indexOf, which expects a string argument, not a regular expression.

Upvotes: 5

Related Questions