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?
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.
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.
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.
String operations will always be faster than regular expression operations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With