Tony
Tony

Reputation: 351

Javascript match multiple occurrences in a string?

So my current HTML looks like

<p class="comment-post-text">@333<br /> @44<br />@564</p>

I'm trying to create links that looks like

@333 @44 @564

However my result is

@333 @333 @333

and I'm using Regex to verify that if a number comes after the @ symbol, transform the text into a link and link-back to the hash of the next post. It's a quoting system more or less. My problem is that it seems to only be matching the first occurrence of my regex, rather than matching for each occurrence.

$('.comment-post-text').each(function( index ) {
     let text = $( this ).text();
     let matches = text.match(/@(\d+)/);

       if(matches !== null){
        console.log(matches);
        let newText = replaceAll(text, /@(\d+)/, "<a href = '#pi_" + matches[1] + "'>" + matches[0] + "</a><br/>");
        $(this).replaceWith(newText);

       }
    });

  function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

The problem is occurrence here at matches[1] it's only capturing the first occurrence of the pattern so looping through the matches array would be useless. Is there a way to have the matches array hold each occurrence of the match? Any help greatly appreciated.

Upvotes: 1

Views: 281

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You don't need to use the String.prototype.match method to check if there is something to replace. Use the String.prototype.replace method directly with a backreference for the first capturing group $1 and the whole match $& in the replacement string.

$('.comment-post-text').each(function( index ) {
    let text = $( this ).text();
    let newText = text.replace(/@(\d+)/g, "<a href = '#pi_$1'>$&</a><br/>");
    $(this).replaceWith(newText);
});

Upvotes: 1

Related Questions