2015-06-02 77 views

回答

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 + ']'); 
+0

好的,但是這種格式「@ [0],0」到「@ [1],1」中呢? thx –

+0

@JozsefNaghi'var regex = new RegExp('@ \\ ['+ increment +'\\],\ s'+ increment,'gi') html = html.replace(regex,'@ ['+ counter +'],'+ counter);' –

0

用這種方式,你可以消毒動態變量:

html = html.replace(new RegExp("\\["+increment+"\\]", "gi"), '[' + counter + ']'); 

這使用動態值。

相關問題