Ifch0o1
Ifch0o1

Reputation: 924

string.prototype.search('$') returns positive int on every string

I want to check if a string contains any of several symbols, including '$'. But the string.prototype.search() method returns last character index + 1 when searching for '$'

For example:

'abc'.search('$')   //return 3
''.search('$')      //return 0

I want to know why this is happening

Upvotes: 0

Views: 114

Answers (1)

Barmar
Barmar

Reputation: 782683

From MDN:

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

So your call is equivalent to:

'abc'.search(/$/);

$ in a regular expression matches the end of the string. If you want to disable the special meaning, you need to escape it:

'abc'.search('\\$')

You need two \ characters: the first escapes the backslash in the string literal, and this then escapes the dollar sign in the regexp. Or you could write:

'abc'.search(/\$/)

Upvotes: 4

Related Questions