在javascript中替换令牌

时间:2010-05-17 16:42:40

标签: javascript regex

我需要实现的是

在字符串中查找模式,存储匹配将匹配替换为唯一的标记,以便后面的标记可以替换为之前找到的匹配。

解释

例如我有一系列模式

paterns = [/Mr\.\s/,/Mrs\.\s/];


stringSubject = "Mr. john is an expert. mrs. john is no less. mr. watson know this very well";

提取匹配后,它可能看起来像(不区分大小写的匹配)

stringSubject = "{1} john is an expert. {2} john is no less. {3} watson know this very well";

并且标记数组可能看起来像

tokens = ["Mr.","mr.","mrs."]

stringSubject = "{1} john is an expert. {3} john is no less. {2} watson know this very well";

//处理stringSubject

之后

令牌被替换为

stringSubject = "Mr. john is an expert. mrs. john is no less. mr. watson know this very well";

这样即使在对匹配模式执行不区分大小写的操作之后,也会检索原始字符串。

如何使用正则表达式完成?

1 个答案:

答案 0 :(得分:2)

这是怎么回事?

var stringSubject = "Mr. john is...",
    patterns = [/Mr\.\s/, /Mrs\.\s/],
    currentTokenIndex = 0,
    tokens = [/* this is where the matches will be stored */];

for (var i = -1, l = patterns.length; ++i < l;) {
    stringSubject = stringSubject.replace(patterns[i], function(match){
        tokens[currentTokenIndex] = match;
        return '{' + currentTokenIndex++ + '}';
    });
}

stringSubject; // <= "{0}john is..."

// Later:
stringSubject = stringSubject.replace(/\{(\d+?)\}/g, function(match, index){
    return tokens[index];
});

stringSubject; // <= "Mr. john is..."