2012-10-02 66 views
1

爲什麼這段代碼不能正常工作?Javascript替換函數不能與正則表達式工作

var temp = "@TEMP (A1)" 
var text = "1st Oct @TEMP (A1)" 
text = text.replace(new RegExp(temp, "gi"), ""); 
console.log(text); //I get same text even though I used replace instead of 1st Oct?? 

任何人都可以解釋這裏出了什麼問題嗎?

回答

6

需要引用正在被直接用作正則表達式的temp特殊字符。 ()字符將字符分組爲模式,而不是實際匹配'('和')'。

4

括號中的正則表達式,除非有逃脫特殊的意義:

var temp = "@TEMP \\(A1\\)" 
1
var temp = "@TEMP \\(A1\\)"; 
var text = "1st Oct @TEMP (A1)"; 
text = text.replace(new RegExp(temp, "gi"), ""); 
console.log(text); 

花括號在正則表達式特殊字符,你應該用反斜槓逃脫它。

相關問題