如何使用 JavaScript 正则表达式在单词边界之间找到用户提供的字符串?

发布于 2024-12-13 13:34:56 字数 641 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩物 2024-12-20 13:34:56
userString.replace(/([\[\]*+.?{}()\\^$])/g, "\\$1")
userString.replace(/([\[\]*+.?{}()\\^$])/g, "\\$1")
渔村楼浪 2024-12-20 13:34:56

您需要正确转义反斜杠。要匹配正则表达式中的单个反斜杠,您需要将其转义一次才能将其接受为正则表达式中的实际反斜杠。当您将正则表达式存储为字符串时,您需要再次对这两个反斜杠进行转义,从而得到 \\\\。因此,您可以简单地在 userString 中转义斜杠:

userString = userString.replace(/\\/g, '\\\\');

请注意,无论如何您都应该清理用户输入,以免人们想出一些奇怪的正则表达式来扰乱您的应用程序。

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 your userString:

userString = userString.replace(/\\/g, '\\\\');

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文