[英]Search for a string with a point in JavaScript
When I try to seach for a string with a point (ie '1.'
), js also points to substrings with commas instead of points. 当我尝试搜索带点的字符串(即
'1.'
)时,js也指向带有逗号而不是点的子串。 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? 有谁知道为什么JavaScript表现如此? Is there a way to search for exactly passed string?
有没有办法搜索确切传递的字符串?
The
search()
method executes a search for a match between a regular expression and thisString
object.search()
方法执行搜索正则表达式与此String
对象之间的匹配。
.
has a special meaning in Regular Expressions. 在正则表达式中有特殊含义。 You need to escape the
.
你需要逃避
.
before matching it. 在匹配之前。 Try the following:
请尝试以下方法:
console.log('xxx1,xxx'.search('1\\\\.'));
indexOf() method should work fine in this case indexOf()方法在这种情况下应该可以正常工作
'1,'.indexOf('1.');
The above code should return -1 上面的代码应该返回-1
String.search is taking regex as parameter. String.search以正则表达式为参数。
Regex evaluate .
正则表达式评估
.
by any character
; 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,'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.