0

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 
2
  • I think you want to use document.querySelectorAll instead of document.querySelector.. With document.querySelector you will get only the first match... Commented Apr 8, 2013 at 12:51
  • @fernandosavio: Hey thanks, but it doesn't work.. Commented Apr 8, 2013 at 14:30

1 Answer 1

2

That is because

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

This is your solution :

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks! It's work, but there is an issue. Please see the update code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.