admin管理员组文章数量:1405386
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,'));
本文标签: Search for a string with a point in JavaScriptStack Overflow
版权声明:本文标题:Search for a string with a point in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744245586a2596995.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论