如何使用 JavaScript 正则表达式在单词边界之间找到用户提供的字符串?
我正在使用 JavaScript 搜索一段文本。我让用户指定一个任意字符串,然后我想搜索该字符串,条件是它被视为“整个单词”,即位于单词边界之间。
我只想能够说例如,
var userString = "something blah";
// => "blah another thing blah"
"blah something blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
// no match, good
"blahsomething blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
userString = "something\\blah";
// want to match, but doesn't
"blah something\\blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
如您所见,它会分解为特殊字符——我需要一种方法来告诉 RegExp 转义用户输入,或者将表达式的一部分留作文字。这在 JavaScript 中可能吗?
I have a body of text that I'm searching using JavaScript. I let the user specify an arbitrary string, then I want to search for that string, with the condition that it is treated as a "whole words", i.e. is between word boundaries.
I just want to be able to say e.g.
var userString = "something blah";
// => "blah another thing blah"
"blah something blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
// no match, good
"blahsomething blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
userString = "something\\blah";
// want to match, but doesn't
"blah something\\blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
As you can see, it breaks down for special characters -- I need a way to tell the RegExp to escape user input, or to set aside a part of the expression as a literal. Is this possible in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要正确转义反斜杠。要匹配正则表达式中的单个反斜杠,您需要将其转义一次才能将其接受为正则表达式中的实际反斜杠。当您将正则表达式存储为字符串时,您需要再次对这两个反斜杠进行转义,从而得到
\\\\
。因此,您可以简单地在userString
中转义斜杠:请注意,无论如何您都应该清理用户输入,以免人们想出一些奇怪的正则表达式来扰乱您的应用程序。
You need to escape the backslashes correctly. To match a single backslash within a regular expression you need to escape it once to have it accepted as an actual backslash within the regular expression. And as you store the regular expression as a string, you need to escape each of those two backslashes again, resulting in
\\\\
. So you can simply escape slashes in youruserString
:Note that you should sanitize your user input anyway so that people don’t come up with some weird regular expressions that mess up your application.