在javascript中查找和替换令牌

时间:2010-05-06 09:44:38

标签: javascript regex

我必须做这样的事情

string  = " this is a good example to show"

search  = array {this,good,show}

使用像

这样的标记查找并替换它们
string  = " {1} is a {2} example to {3}" (order is intact)

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

string  = " {1} is a {2} numbers to {3}" (order is intact)

标记再次被替换回字符串likem,以便字符串变为

string  = " this is a good number to show"

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

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

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

提前致谢。

2 个答案:

答案 0 :(得分: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];
});

答案 1 :(得分: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]);
}