我正在尝试使用一些正则表达式将“或”一词包装在某些标记的<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>
结果嵌套第二个<a> 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>
答案 0 :(得分:0)
括号内匹配的内容是group=c(1,1,2,2,3,4,4,5,5,6)
变量中返回的内容。您只需要包含要替换的文本:
$1
或者如果您想匹配链接之间的任何单词:
html = html.replace( /<\/a>( or )<a/, "<\/a><span class='or'>$1</span><a" );