在javascript中查找和替换令牌 [英] find and replace tokens in javascript

查看:98
本文介绍了在javascript中查找和替换令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做这样的事情

string  = " this is a good example to show"

search  = array {this,good,show}

使用类似的标记查找并替换它们

find and replace them with a token like

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

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

the string will undergo some processing and then

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

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

tokens are again replaced back to the string likem so that the string becomes

string  = " this is a good number to show"

如何确保模式匹配且相同的令牌是替换

how to make sure that the pattern is matched and the same tokens are replaced

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

for example /[gG]ood/ is a pattern to search and replaced later with appropriate "case".Or in other words if ^\s*[0-9]+. is the pattern the matched string needs to be stored and replace to form the original text as it was

应该如何实现以使该过程以高性能完成?

How should it be implemented so that the process is done at high performance ?

提前致谢。

推荐答案

你没有提及任何事情关于字符串中多次出现相同的标记,我猜你会替换所有出现的事件。

You don't mention anything about multiple occurrences of the same token in the string, I guess you'll be replacing all occurrences.

它会是这样的:

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]);
}

这篇关于在javascript中查找和替换令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆