正则表达式不匹配

时间:2016-11-16 13:05:39

标签: javascript regex string

我试图用正则表达式替换部分textarea文本。

propertiesText是从textarea收到的全文,替换代码如下:

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使其正常工作。

我的代码中缺少什么?

1 个答案:

答案 0 :(得分:3)

String Replace不会实际更新当前字符串,而只是返回一个应用了replace的新字符串。所以要将代码更新修复为

propertiesText = propertiesText.replace(regexExpression, newString);

请参阅http://www.w3schools.com/jsref/jsref_replace.asp

  

replace()方法在字符串中搜索指定的值或正则表达式,并返回一个替换指定值的新字符串。

相关问题