Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
skeggse Avatar asked Jul 19 '12 20:07

skeggse


People also ask

What is the purpose of STR search regex?

Using String Methods The search() method uses an expression to search for a match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced.

Is a string a regex?

In formal language theory, a regular expression (a.k.a. regex, regexp, or r.e.), is a string that represents a regular (type-3) language. Huh?? Okay, in many programming languages, a regular expression is a pattern that matches strings or pieces of strings.

What are regular expressions search a string using regular expressions?

A regular expression is a form of advanced searching that looks for specific patterns, as opposed to certain terms and phrases. With RegEx you can use pattern matching to search for particular strings of characters rather than constructing multiple, literal search queries.

Are regular expression better then string functions?

String operations will always be faster than regular expression operations.


1 Answers

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.

like image 111
apsillers Avatar answered Oct 12 '22 08:10

apsillers