javascript - javascript中的 token 替换

标签 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";

token 数组可能看起来像

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

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

//处理stringSubject之后

token 被替换为

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

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

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

最佳答案

这个怎么样?

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..."

关于javascript - javascript中的 token 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2850948/

相关文章:

javascript - 不工作 Jquery

javascript - Ember.js URL 如何表示每个可能的路由器状态?

javascript - 用于验证字段的正则表达式

regex - sed 替换匹配复杂正则表达式模式的文本

python - 不同行的文本替换

c# - 货币的正则表达式缺少个位数?

regex - Swift - 将属性字符串添加到括号中的项目

javascript - 使用 amCharts 格式化 labelText

javascript - 从 Controller 动态添加类

javascript - 如果有 "onselectstart",是否有 "onselectend"?