简体   繁体   English

正则表达式替换(外部)两个标签之间的文本

[英]Regex to replace text between (outside) two tags

I am trying to use some regex to wrap the word "or" in a <span> tag in some markup.我正在尝试使用一些正则表达式将单词“或”包裹在某些标记中的<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 );

The resulting markup is a bit strange:结果标记有点奇怪:

<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>

The result nests the second <a> inside of the ` element.结果将第二个<a> inside of the ` 元素内。 I can't seem to wrap my head around why it's nesting in such a weird way.我似乎无法理解为什么它以如此奇怪的方式嵌套。

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

I've got a fiddle where I was testing some things here: https://jsfiddle.net/qfuLozxw/我有一个小提琴,我在这里测试了一些东西: https : //jsfiddle.net/qfuLozxw/

Intended results:预期结果:

<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>

The content matched inside your parenthesis is what gets returned in the $1 variable.括号内匹配的内容是$1变量中返回的内容。 You just need to contain the text you want to replace:您只需要包含要替换的文本:

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

Or if you want to match on any word inbetween your links:或者,如果您想匹配链接之间的任何单词:

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

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

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

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