javascript - 正则表达式不匹配

标签 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 ,它正在工作。

我的代码中缺少什么?

最佳答案

字符串替换不会实际更新当前字符串,而只是返回应用了替换的新字符串。因此,要将您的代码更新为

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/

相关文章:

javascript - js比较两个字符串

c - 将字符串中的 n 个字符传递给 C 中的函数

swift - 如何在 Swift 中限制字符串或属性字符串中的字符数

java - 如何计算 ArrayList 中的唯一值?

javascript - 同步 Ajax 请求

javascript - 想要重定向到特定部分 id 上的下一页,而不在 url 中显示 #id

javascript - 这段代码有什么作用吗?

php - 正则表达式拆分 TitleCase Word

regex - 学习正则表达式

javascript - jstree中如何获取选中节点的所有子节点