Vun-Hugh Vaw
Vun-Hugh Vaw

Reputation: 180

Why does "a".search(".") return 0 in JavaScript?

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

Answers (5)

Ry-
Ry-

Reputation: 224903

From MDN:

The search() method executes a search for a match between a regular expression and this String object.

If a non-RegExp object regexp is passed, it is implicitly converted to a RegExp with new 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

Dipak R
Dipak R

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

Gray Hat
Gray Hat

Reputation: 368

. matches any character except for line terminators. Therefore, "a".search(".") returns 0.

matches a at 0 index.

Upvotes: 0

Pranav Rustagi
Pranav Rustagi

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

sonEtLumiere
sonEtLumiere

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

Related Questions