gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:07:54 26 4
gpt4 key购买 nike

我正在尝试使用一些正则表达式将单词“or”包装在 <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>

我有一个 fiddle ,我在这里测试一些东西: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>

最佳答案

括号内匹配的内容是 $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/

关于javascript - 正则表达式替换两个标签之间(外部)的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60441161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com