Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for a string with a point in JavaScript

When I try to seach for a string with a point (i.e. '1.'), js also points to substrings with commas 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?

like image 317
S. Entsov Avatar asked Sep 23 '26 02:09

S. Entsov


2 Answers

Per the docs:

The search() method executes a search for a match between a regular expression and this String 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\\.'));
like image 93
31piy Avatar answered Sep 25 '26 14:09

31piy


Use indexOf().

let str = "abc1,231.4";
console.log(str.indexOf("1."));
like image 28
Scott Marcus Avatar answered Sep 25 '26 14:09

Scott Marcus