4

想象一下,我有以下多行 Javascript 字符串:

学校

苹果

~胡萝卜

我想取任何以“~”开头的行并将其替换为“#(contents of line)#”。所以在这个例子中,我想找到“~carrot”并将其替换为“#carrot#”。

我正在尝试使用正则表达式提出解决方案,但无法找到用修改后的版本(带有前置/附加字符)替换某些匹配字符串的方法。

任何帮助将不胜感激,希望一个例子能打开灯泡......

4

2 回答 2

9

thestring.replace(/~(\w+)/g, "#$1#");

括号“捕获”单词 ( \w+),$1结果中的 引用捕获的内容。

于 2012-08-21T14:26:53.353 回答
-1

这真的很容易。假设您在 OldString 中有您的字符串

var OldString = "school apple  ~carrot dog";

var myNewString = OldString.replace(/~carrot/, "#carrot#");

document.write("Old string =  " + OldString); 
document.write("<br />New string = " + myNewString);

希望能帮助到你

于 2012-08-21T14:27:43.807 回答