简体   繁体   English

使用JavaScript动态键的正则表达式

[英]Regex with dynamic keys in Javascript

I have an object, and inside my HTML I use tags of the form [itemkey] to refer to the value of the itemkey property of that object, and want to replace these tags with their values. 我有一个对象,并且在我的HTML中,我使用[itemkey]形式的标签来引用该对象的itemkey属性的值,并希望将这些标签替换为其值。 My JavaScript code looks like this: 我的JavaScript代码如下所示:

_.forEach(objectItem,function(val,key){
  var re = new RegExp('\[' + key +'\]','g');
  htmlDump = htmlDump.replace(re,val)
});

But it does not work. 但这行不通。 What is wrong? 怎么了?

Whatever manipulation of the HTML you do, nothing you do will have any effect until you replace the HTML of the document. 无论您对HTML进行什么操作,在替换文档的HTML之前,您所做的任何事情都不会有任何效果。

Other than that, there is no logical reason why @Tushar's approach as given in the first comment would not work (except that it needed a g flag): 除此之外,没有逻辑上的原因导致第一个评论中的@Tushar的方法行不通(除了它需要一个g标志):

new RegExp('\\[' + key + '\\]', 'g');

Overall, this approach is flawed. 总的来说,这种方法是有缺陷的。 You are replacing the entire HTML; 您将替换整个HTML; for instance, that will wipe out all event listeners. 例如,这将清除所有事件侦听器。 Instead, you should iterate through the DOM and apply your transformation to each text node. 相反,您应该遍历DOM并将转换应用于每个文本节点。

Please be aware that ideally you should be escaping the key in order to avoid regexp-related characters in it from breaking the regexp. 请注意,理想情况下,您应该转义key ,以避免其中与regexp相关的字符破坏regexp。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM