【问题标题】:Regex to replace text between (outside) two tags正则表达式替换(外部)两个标签之间的文本
【发布时间】:2020-06-11 22:25:29
【问题描述】:

我正在尝试使用一些正则表达式将单词“或”包装在某个标记中的 <span> 标记中。

<div id="test">
  <a href="#" class="thickbox open-details-modal" aria-label="View version 1.5.29 details">View version 1.5.29 details</a> or <a href="#" class="update-link" aria-label="Update now">update now</a>
</div>

<div id="result"></div>
var html = $( '#test' ).html();

html = html.replace( /(<\/a>[\s\S]*?<a)/, "<\/a><span class='or'>$1<\/span><a href" );

$( '#result' ).html( html );

生成的标记有点奇怪:

<div id="result">
  <a href="#" class="thickbox open-details-modal" aria-label="View version 1.5.29 details">View version 1.5.29 details</a><span class="or"> or <a< span=""><a href="" class="update-link" aria-label="Update now">update now</a>
</a<></span></div>

结果嵌套了第二个&lt;a&gt; inside of the` 元素。我似乎无法理解为什么它以如此奇怪的方式嵌套。

<span class="or"> or <a< span=""><a href="" class="update-link" aria-label="Update now">update now</a>
</a<></span>

我有一个小提琴,我在这里测试一些东西:https://jsfiddle.net/qfuLozxw/

预期结果:

<div id="test">
  <a href="#" class="thickbox open-details-modal" aria-label="View version 1.5.29 details">View version 1.5.29 details</a> <span class="or">or</span> <a href="#" class="update-link" aria-label="Update now">update now</a>
</div>

【问题讨论】:

标签: javascript regex replace


【解决方案1】:

括号内匹配的内容是在$1 变量中返回的内容。您只需要包含要替换的文本:

html = html.replace( /<\/a>( or )<a/, "<\/a><span class='or'>$1</span><a" );

或者,如果您想匹配链接之间的任何单词:

html = html.replace( /<\/a>( \w* )<a/, "</a><span class='or'>$1</span><a" );

示例在这里:https://jsfiddle.net/wbard38q/

【讨论】:

  • 这有帮助还是您仍然有问题?