[英]Javascript: Replace all occurences of ' a ' in a string with ' b ' with a regex
[英]Replacing all occurences in a string in javascript issue
這是我的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 + ']');
使用這種方式:
html = html.replace(new RegExp("\\["+increment+"\\]", "gi"), '[' + counter + ']');
這利用了動態值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.