HTML将文本转换为链接

时间:2013-04-08 12:12:36

标签: javascript html parsing dom

我有这个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 

1 个答案:

答案 0 :(得分:2)

那是因为

"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;
});