我正在尝试替换 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;
在控制台中,我得到以下正则表达式:
但是原始 propertiesText
中的文本没有被替换:
我尝试检查我的正则表达式和 you can see it is matching .
我还尝试使用输出的相同正则表达式隔离替换代码部分,并且 as you can see again ,它正在工作。
我的代码中缺少什么?
最佳答案
字符串替换不会实际更新当前字符串,而只是返回应用了替换的新字符串。因此,要将您的代码更新为
propertiesText = propertiesText.replace(regexExpression, newString);
参见http://www.w3schools.com/jsref/jsref_replace.asp
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
关于javascript - 正则表达式不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40632918/