I have this html code:
<h2>A</h2>
<span>
<p>Compare BookA. 12:2; BookB. 41:4; 44:6; BookC. 1:11,17; 2:8.</p>
</span>
And this 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>
I use this to produce what I want:
txt = txt.replace(/(BookA|BookB|BookC)\. ([\d:,; -]+)/g, function (match, book, verses)
But it returns like:
<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>
When I tried this:
txt = txt.replace(/(BookA)\. ([\d:,; -]+)/g, function (match, book, verses)
It returns like below:
Compare <a>BookA. 12:2</a> <a>BookA</a> BookB. 41:4; 44:6; BookC. 1:11,17; 2:8.
What I want to get is somethings like:
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>
Any ideas? Thanks.
UPDATE
Thanks to Alytrem's Solution. But I still have a problem, suppose that there is a number before the verse:
txt = txt.replace(/(1 BookA|2 BookA|BookB)\. ([\d:,; -]+)/g, function (match, book, verses)
And I have this kind of words:
1 BookA 15:3; 2 BookA 11:20-22
It will returns like:
<a>1 BookA 15:3</a> <a>1 BookA 2</a> BookA 11:20-22