最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Search for a string with a point in JavaScript - Stack Overflow

programmeradmin7浏览0评论

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, against 1. or vice versa. Anyway, use a regex – j08691 Commented Jun 15, 2018 at 14:33
Add a ment  | 

4 Answers 4

Reset to default 5

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\\.'));

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,'));  

发布评论

评论列表(0)

  1. 暂无评论