如何在Javascript中使用正则表达式中的变量 [英] How to use variables inside Regular Expression in Javascript

查看:366
本文介绍了如何在Javascript中使用正则表达式中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中构建一个与单词匹配但不属于它的RegEx。我认为像\ bword \这样的东西适用于此。我的问题是这个词是事先不知道的,所以我想使用一个变量来组装正则表达式,该变量持有要匹配的字符串:

I want to build a RegEx in JavaScript that matches a word but not part of it. I think that something like \bword\b works well for this. My problem is that the word is not known in advance so I would like to assemble the regular expression using a variable holding the word to be matched something along the lines of:

r = "\b(" + word + ")\b";
reg = new RegExp(r, "g");
lexicon.replace(reg, "<span>$1</span>"

我注意到的,不起作用。我的想法是用段落标记替换段落中的特定单词。有人可以帮助我吗?

which I noticed, does not work. My idea is to replace specific words in a paragraph with a span tag. Can someone help me?

PS:我正在使用jQuery 。

PS: I am using jQuery.

推荐答案

\ 是正则表达式中的转义字符在字符串中。

\ is an escape character in regular expressions and in strings.

由于您是从字符串组装正则表达式,因此必须转义 \ s in。

Since you are assembling the regular expression from strings, you have to escape the \s in them.

r = "\\b(" + word + ")\\b";

应该可以解决问题,尽管我还没有测试过。

should do the trick, although I haven't tested it.

您可能不应该使用全局 r (并且可能不适用于 reg 或者)。

You probably shouldn't use a global for r though (and probably not for reg either).

这篇关于如何在Javascript中使用正则表达式中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆