gpt4 book ai didi

javascript - HTML 将文本转换为链接

转载 作者:行者123 更新时间:2023-12-02 18:50:28 25 4
gpt4 key购买 nike

我有这个 html 代码:

<h2>A</h2>
<span>
<p>Compare BookA. 12:2; BookB. 41:4; 44:6; BookC. 1:11,17; 2:8.</p>
</span>

还有这个 JavaScript:

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var span = document.querySelector('span');

txt = span.innerHTML;

txt = txt.replace(/(BookA)\. ([\d:,; -]+)/g, function (match, book, verses) {
var link = '';
verses.split(/;\s+/).forEach(function (elem) {
if(elem.length > 0) // <== Alytrem's Solution
link += '<a>' + book + ' ' + elem + '</a> ';
});
return link;
});
span.innerHTML = txt;
}//]]>
</script>

我用它来生产我想要的东西:

txt = txt.replace(/(BookA|BookB|BookC)\. ([\d:,; -]+)/g, function (match, book, verses)

但它返回的是这样的:

<a>BookA 12:2</a> <a>BookA</a> <a>BookB 41:4</a> <a>BookB 44:6</a> <a>BookB</a> <a>BookC 1:11,17</a> <a>BookC 2:8</a>

当我尝试这个时:

txt = txt.replace(/(BookA)\. ([\d:,; -]+)/g, function (match, book, verses)

它返回如下:

Compare <a>BookA. 12:2</a> <a>BookA</a> BookB. 41:4; 44:6; BookC. 1:11,17; 2:8.

我想要得到的是这样的:

Compare <a>BookA. 12:2</a> <a>BookB. 41:4</a> <a>BookB. 44:6</a> <a>BookC. 1:11,17</a> <a>BookC. 2:8</a>

有什么想法吗?谢谢。

<小时/>

更新

感谢 Alytrem 的解决方案。但我还有一个问题,假设这节经文之前有一个数字:

txt = txt.replace(/(1 BookA|2 BookA|BookB)\. ([\d:,; -]+)/g, function (match, book, verses)

我有这样的话:

1 BookA 15:3; 2 BookA 11:20-22

它将返回如下:

<a>1 BookA 15:3</a> <a>1 BookA 2</a> BookA 11:20-22 

最佳答案

那是因为

"12:2; ".split(/;\s+/) gives you ["12:2",""].

这是您的解决方案:

txt.replace(/(BookA|BookB|BookC)\. ([\d:,; -]+)/g, function (match, book, verses) {
var link = '';
verses.split(/;\s+/).forEach(function (elem) {
if(elem.length > 0) // <== solution
link += '<a>' + book + ' ' + elem + '</a> ';
});
return link;
});

关于javascript - HTML 将文本转换为链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878748/

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