在javascript中查找和替换令牌

Sou*_*abh 3 javascript regex

我必须做这样的事情

string  = " this is a good example to show"

search  = array {this,good,show}
Run Code Online (Sandbox Code Playgroud)

找到并用像这样的标记替换它们

string  = " {1} is a {2} example to {3}" (order is intact)
Run Code Online (Sandbox Code Playgroud)

字符串将经过一些处理然后

string  = " {1} is a {2} numbers to {3}" (order is intact)
Run Code Online (Sandbox Code Playgroud)

令牌再次被替换回字符串likem,以便字符串变为

string  = " this is a good number to show"
Run Code Online (Sandbox Code Playgroud)

如何确保模式匹配并替换相同的标记

例如/ [gG] ood /是一个搜索模式,稍后用适当的"case"替换.或者换句话说,如果^\s*[0-9] +.是匹配的字符串需要存储和替换的模式,以形成原始文本

如何实施以使流程以高性能完成?

提前致谢.

RoT*_*oRa 7

var string = "this is a good example to show"
var search = ["this","good","show"] // this is how you define a literal array

for (var i = 0, len = search.length; i < len; i++) {
   string.replace(RegExp(search[i], "g"), "{" + (i+1) + "}")
}

//... do stuff

string.replace(/\{(\d+)\}/, function(match, number) {
  if (+number > 0)
    return search[+number - 1];
});
Run Code Online (Sandbox Code Playgroud)


Dan*_*rzo 6

你没有提到任何关于字符串中多次出现相同令牌的事情,我猜你将会替换所有出现的事件.

它会是这样的:

var string = "This is a good example to show, this example to show is good";
var tokens = ['this','good','example'];

for (var i = 0; i < tokens.length; i++) {
    string.replace(new RegExp(tokens[i], "g"),"{"+i+"}");
}
// string processing here
for (var i = 0; i < tokens.length; i++) {
    string.replace(new RegExp("{"+i+"}","g"),tokens[i]);
}
Run Code Online (Sandbox Code Playgroud)

  • 正则表达式必须转义{和}或它是一个无效的语法:`string.replace(new RegExp("\\ {"+ i +"\\}","g"),tokens [i]);` (3认同)