Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use jQuery's .each() to replace text / regex?

I have this code right here:

var tweetText = $("#tweet_text").text();
var replaced = replace(tweetText);

document.getElementById("tweet_text").innerHTML = replaced;

It gets text from a text element, and highlights the mentions and URLS to make them clickable. Here is the replace() code:

function replace(text) {
    return text.replace(/([@#])([a-z\d_]+)/ig, function(_, marker, tag) {
        if (marker === "@")
            return '<a href="?r=site/twitterprofile&q=$1">' + "@" + tag + '</a>';
        return '<a href="?r=site/hashtag&q=$2">' + "#" + tag + '</a>';
    });
}

I have a long list of divs / tweets, and when I run replace() it only applies the pattern matching function to one div. To get around this, I thought of collecting all of the #tweet_textdivs using .each(), and then applying the replace() function once it loops through.

Could somebody help me do that please?

like image 970
user3776241 Avatar asked Oct 23 '25 17:10

user3776241


1 Answers

$('.your-tweet-class').each(function() {
    $(this).text( replace( $(this).text() ) );
});

You can remove the spaces, I just put them in for clarity.

like image 107
Ben Fried Avatar answered Oct 26 '25 05:10

Ben Fried



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!