[英]global replace doesn't work , but simple replace works fine
i have a simple smily parser code : 我有一个简单的笑脸解析器代码:
for (var key in smiles) {
text = text.replace(key , smiles[key]);
}
return text;
so the problem is , this will only replace the first one so i've switched to global replace 所以问题是,这只会替换第一个,所以我切换到了全局替换
for (var key in smiles) {
var r = '/'+key+'/g';
console.log(r);
text = text.replace(r , smiles[key]);
}
in console i have : 在控制台中,我有:
/:)/g
/;)/g
/:(/g
which seems to be ok , but it wont replace any of these codes :) ;) :(
whats wrong ? 这似乎可以,但是它不会替换任何这些代码
:) ;) :(
怎么了?
A regular expression literal ( /foo/g
) is not the same as a string that looks like a regular expression literal ( "/foo/g"
). 正则表达式文字(
/foo/g
)与看起来像正则表达式文字( "/foo/g"
)的字符串不同。
You can create regular expressions dynamically using the RegExp
constructor: 您可以使用
RegExp
构造函数动态创建正则表达式:
var r = new RegExp(key, 'g');
And that's the point at which you'll get parenthesis-related errors. 这就是与括号相关的错误的关键所在。 You can escape your values to put in a regular expression – put together in the nicest way, it might look something like this:
您可以对值进行转义以放入正则表达式 –以最佳方式将其组合在一起,它可能看起来像这样:
function escapeRegex(text) {
return text.replace(/[[{}()*+?.\\^$|]/g, "\\$&");
}
function replaceAll(str, map) {
var re = new RegExp(Object.keys(map).map(escapeRegex).join("|"), "g");
return str.replace(re, function(m) {
return map[m];
});
}
Just keep looping through the text and replacing the smiley until there are no more occurrences:- 只需不断浏览文本并替换笑脸,直到不再出现:-
for (var key in smiles) {
while (text.indexOf(key) > -1) {
text = text.replace(key, smiles[key]);
}
}
return text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.