Javascript替换方括号之间的regexp字符串

时间:2017-11-21 08:15:50

标签: javascript regex

我需要替换javascript变量中的所有[counter]出现。我不知道为什么我不能使它工作,因为当我使用像https://regex101.com/这样的在线正则表达式工具时,它匹配我想要的[计数器] -occurences。

enter image description here

要替换的示例字符串:

<div id="ITEM-9" data-widget-id="9" data-widget-type="CounterWidget" data-counter="6" data-icon="fa fa-bell" data-filterid="2" data-hidewhenzero="1" data-countervalue="[counter]" class="cust-masonry-item col-xs-6 col-sm-4 col-md-3 col-lg-3 cust-masonry-item-height-1 ng-scope" style="position: absolute; left: 74.9035%; top: 0px;"><div class="cust-masonry-item-content"><div class="cust-dashboard-counter"><span class="cust-dashboard-counter-icon"><span class="fa fa-bell"></span></span><span class="cust-dashboard-counter-title cust-readable-text">API</span><span class="cust-dashboard-counter-count"><span class="cust-dashboard-counter-number">[counter]</span><span class="cust-dashboard-counter-subscript cust-readable-text">&nbsp;Log messages to read</span></span></div></div></div>

我尝试用'替换'替换[counter] -strings,如下所示:

var newHTML = element[0].outerHTML.toString().replace('/(\[counter\])/g', 'replaced');

预期结果:

<div id="ITEM-9" data-widget-id="9" data-widget-type="CounterWidget" data-counter="6" data-icon="fa fa-bell" data-filterid="2" data-hidewhenzero="1" data-countervalue="replaced" class="cust-masonry-item col-xs-6 col-sm-4 col-md-3 col-lg-3 cust-masonry-item-height-1 ng-scope" style="position: absolute; left: 74.9035%; top: 0px;"><div class="cust-masonry-item-content"><div class="cust-dashboard-counter"><span class="cust-dashboard-counter-icon"><span class="fa fa-bell"></span></span><span class="cust-dashboard-counter-title cust-readable-text">API</span><span class="cust-dashboard-counter-count"><span class="cust-dashboard-counter-number">replaced</span><span class="cust-dashboard-counter-subscript cust-readable-text">&nbsp;Log messages to read</span></span></div></div></div>

是的,我确信outerHTML包含上面的字符串,但是我的单词不会被替换。

我现在感到很愚蠢......感谢你指点我正确的方向。

1 个答案:

答案 0 :(得分:1)

正则表达式不是字符串

newHTML = element[0].outerHTML.toString().replace(/(\[counter\])/g, "replaced");