When I try to seach for a string with a point (i.e. '1.'
), js also points to substrings with mas instead of points. It's better to look at the example:
'1,'.search('1.'); // 0
'xxx1,xxx'.search('1.'); // 3
// Normal behaviour
'1.'.search('1,'); // -1
Does anyone know why JavaScript behave itself so? Is there a way to search for exactly passed string?
When I try to seach for a string with a point (i.e. '1.'
), js also points to substrings with mas instead of points. It's better to look at the example:
'1,'.search('1.'); // 0
'xxx1,xxx'.search('1.'); // 3
// Normal behaviour
'1.'.search('1,'); // -1
Does anyone know why JavaScript behave itself so? Is there a way to search for exactly passed string?
Share Improve this question edited Jun 15, 2018 at 14:31 S. Entsov asked Jun 15, 2018 at 14:28 S. EntsovS. Entsov 536 bronze badges 1-
In none of your examples does the search string match the string provided. You're always trying to match
1,
against1.
or vice versa. Anyway, use a regex – j08691 Commented Jun 15, 2018 at 14:33
4 Answers
Reset to default 5Per the docs:
The
search()
method executes a search for a match between a regular expression and thisString
object.
.
has a special meaning in Regular Expressions. You need to escape the .
before matching it. Try the following:
console.log('xxx1,xxx'.search('1\\.'));
Use indexOf()
.
let str = "abc1,231.4";
console.log(str.indexOf("1."));
indexOf() method should work fine in this case
'1,'.indexOf('1.');
The above code should return -1
String.search is taking regex as parameter.
Regex evaluate .
by any character
; you gotta escape it using double anti-slash \\
.
console.log('1,'.search('1\\.'));
console.log('xxx1,xxx'.search('1\\.'));
console.log('xxx1.xxx'.search('1\\.'));
console.log('1.'.search('1,'));