English 中文(简体)
如何在 Java稿中经常表述中使用变量
原标题:How to use variables inside Regular Expression in Javascript

我想在 Java文中建造一个与文字一致但并非部分内容的雷Ex。 我认为,像字句这样的话对这一点很有好处。 我的问题是,这个词没有事先知道,因此,我要用一个可变的词组起来,其措辞大致如下:

r = "(" + word + ")";
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:我正在使用j Query。

最佳回答

由于你将定期表达从插头上来,你必须躲避在上面的<条码>。

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

尽管我有点对此进行了测试,但还是应当做到。

您或许会不使用全球代码<>r(但可能不使用<代码>/>>。

问题回答

你们不要放弃反弹。 因此,你应当:

r = "\b(" + word + ")\b"; //Note the double backslash
reg = new RegExp(r, "g");

而且,你应该从文字上逃脱特殊性,因为你不知道它是否具有特殊性。

希望这一帮助。 卡车

而不要在格罗舍普变量中书写字句,因为它不发挥作用!

例(不工作):

 var r = "^\w{0,"+ maxLength-1 +"}$";    // causes error
 var reg = new RegExp(r, "g");

例例,按预期恢复体积:

 var m = maxLength - 1;
 var r = "^\w{0,"+ m +"}$";
 var reg = new RegExp(r, "g");

使用

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




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签