这是我的js代码:
html = html.replace("/["+increment+"]/gi", '[' + counter + ']');
其中增量为 0,计数器为 1 或
html = html.replace("/[0]/gi", '[1]');
我的版本不会将字符串中的 [0] 替换为 [1]。为什么?
最佳答案
您需要使用RegExp构造函数,因为正则表达式是动态的
var regex = new RegExp("\\[" + increment + "\\]", 'gi')
html = html.replace(regex, '[' + counter + ']');
如果需要,您还可以清理动态变量
if (!RegExp.escape) {
//A escape function to sanitize special characters in the regex
RegExp.escape = function (value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
//You could also escape the dynamic value it is an user input
var regex = new RegExp("\\[" + RegExp.escape(increment) + "\\]", 'gi')
html = html.replace(regex, '[' + counter + ']');
关于javascript - 替换javascript问题中字符串中的所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30595727/