0
我有這樣的HTML代碼: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>
任何想法?謝謝。
UPDATE
由於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
我想你想使用[document.querySelectorAll(https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll)代替[文件.querySelector](https://developer.mozilla.org/en-US/docs/DOM/Document.querySelector)..有了document.querySelector,你只會得到第一個匹配... – fernandosavio 2013-04-08 12:51:03
@fernandosavio:嘿謝謝,但它不工作.. – 2013-04-08 14:30:32