Reputation: 180
Why does "a".search(".")
return 0
in JavaScript, even though "".search(".")
returns -1
? Does "."
have a special meaning when used in search()
?
Upvotes: 1
Views: 570
Reputation: 224903
From MDN:
The
search()
method executes a search for a match between a regular expression and thisString
object.⋮
If a non-RegExp object
regexp
is passed, it is implicitly converted to a RegExp withnew RegExp(regexp)
.
That happens in this case, and "."
gets converted to /./
.
.
does have special meaning in JavaScript regular expressions: it matches any non-newline character. "a"
has a non-newline character at position 0, and ""
has no non-newline characters to match.
You might have been thinking of String.prototype.indexOf
, which searches for a string.
console.log("a".indexOf("."));
Upvotes: 4
Reputation: 166
For your query, .
has special meaning in regex
expression. search()
uses regex
in back. So, you have to put escape
character before special character like,
console.log( "".search("\\.") );
Upvotes: 0
Reputation: 368
.
matches any character except for line terminators.
Therefore, "a".search(".")
returns 0.
matches a
at 0
index.
Upvotes: 0
Reputation: 2731
The reason is because .search()
takes regular expression as parameter. And in case you pass a string, it is converted to regular expression implicitly. However, when you talk about ".", on changing it to regular expression, it can become /./
but it needs to be /\./
. That is why, you would have to pass a regular expression in place of a string for ".".
Do it like : "a".search(/\./);
Upvotes: 1
Reputation: 4562
search() method returns the index of the first match, or -1 if no match was found.
console.log("asd".search("d")); // 2
console.log("aasds.asdd".search(/\./)); // 5
The correct syntax to match a dot is by a regex with escape character \.
Upvotes: 0