搜索反斜杠
我有 JavaScript 可以搜索例如。字符串中的一个字母,如果该字母不存在则输出“ok”,如果该字母存在则输出“not ok”:
var term = "term";
var slash = "a";
var search =term.search(slash);
if(search==-1)
"ok";
else
"not ok";
问题是我希望它也能与反斜杠一起使用。 奇怪的是,连续搜索 2 个反斜杠有效,因此“term”输出“ok”,“term\\”输出“not ok”:
var term = "term";
var slash = "\\\\";
var search =term.search(slash);
if(search==-1)
"ok";
else
"not ok";
但是搜索 1 个反斜杠不起作用,因此此代码给出错误:
var term = "term";
var slash = "\\";
var search =term.search(slash);
if(search==-1)
"ok";
else
"not ok";
希望有人看到这个错误。谢谢!
I've JavaScript which searches for eg. a letter in a string and outputs "ok" if the letter is not there and "not ok" if the letter is there:
var term = "term";
var slash = "a";
var search =term.search(slash);
if(search==-1)
"ok";
else
"not ok";
The problem is that I want this to work with a backslash too.
The strange thing is, searching for 2 backslashes in a row works, so "term" outputs "ok" and "term\\" outputs "not ok":
var term = "term";
var slash = "\\\\";
var search =term.search(slash);
if(search==-1)
"ok";
else
"not ok";
But searching for 1 backslash doesn't work, so this code gives an error:
var term = "term";
var slash = "\\";
var search =term.search(slash);
if(search==-1)
"ok";
else
"not ok";
Hope someone sees the error. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 JavaScript 中创建正则表达式涉及两层解释。第一个是 string 语法,并且您已经正确地将反斜杠加倍来解决这一问题。但是,字符串本身将由正则表达式语法分析代码解释,并且将出现单个反斜杠的问题。换句话说,由单个反斜杠组成的正则表达式是语法错误;这是不允许的。如果要搜索单个反斜杠,则需要一个包含两个反斜杠的正则表达式。
使用本机文字正则表达式语法创建正则表达式使这一点更加明显:
There are two layers of interpretation involved with making a regular expression in JavaScript. The first is that of the string syntax, and you've correctly doubled your backslashes to account for that. However, the string will itself be interpreted by the regular expression syntax analysis code, and that will have a problem with a single lone backslash. In other words, a regular expression consisting of a single backslash is a syntax error; it's simply not allowed. If you want to search for a single backslash, you need a regular expression with two backslashes in it.
Making a regular expression with the native literal regular expression syntax makes this more obvious: