Reputation: 924
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
Reputation: 782683
From MDN:
regexp
Optional. A regular expression object. If a non-RegExp objectobj
is passed, it is implicitly converted to aRegExp
by usingnew 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