2016-11-16 47 views
0

我試圖用正則表達式替換textarea文本的部分。正則表達式不會匹配

propertiesTexttextarea收到的全文,並替換代碼如下:

var propertyName = inputs[i].name; 
var propertyValue = inputs[i].value; 

//#regexExpression = #propertyName=.* [example: /#EPCDatabase\/EPCdatabase.param\/epc.db.user=.*$/gim]// 
var regexExpression = new RegExp(propertyName + "=.*$","gim"); 
//#newString = propertyName=propertyValue [example: EPCDatabase\/EPCdatabase.param\/epc.db.user=ddddd]// 
var newString = propertyName.substring(1) + "=" + propertyValue; 
console.log("Regex Expression: " + regexExpression); 
console.log("Replace String: " + newString); 

propertiesText.replace(regexExpression, newString); 
console.log(propertiesText); 
return; 

在控制檯中,我得到了下面的正則表達式:

Console Regex

但原文propertiesText中未被替換:

Properties String after replace

我試過檢查我的正則表達式和you can see it is matching

我也嘗試隔離更換代碼部分與輸出相同的正則表達式,並as you can see again,其工作。

我在代碼中缺少什麼?

回答

3

字符串替換不會acrtally更新當前字符串,但只是返回一個新的字符串與應用替換。因此,要解決您的代碼更新到

propertiesText = propertiesText.replace(regexExpression, newString); 

http://www.w3schools.com/jsref/jsref_replace.asp

的replace()方法搜索指定的值,或正則表達式的字符串,並返回一個新字符串,其中指定的值更換。

+0

該死的我(臉紅),我懷疑替換實際上是替換,但我太盲目,認爲正則表達式是問題。唯一剩下的就是說一個大**謝謝**。 –