Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How replace to same class names with foreach/each?

I have to convert plain text urls to <a href=""></a>. I've found a JS code that works. My problem is that my HTML structure needs that I modify the code, putting the current code inside a foreach.

My html:

<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>

The JS:

$(function()
{
    var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/ig;    
    $('.content').html($('.content').html().replace(re, '<a href="$1" title="">$1</a>'));
});

The above JS works, but will populate all the div's with the same content. I've tried to put this code in a foreach but have failed. My poor JS knowledge makes me ask this on SO.

Can you give some clues on how to put this code in a foreach loop?

like image 911
André Avatar asked Feb 11 '26 01:02

André


1 Answers

Functions like .html allow a function to be passed. An .each loop is then done internally, and moreover you get the current value passed:

$('.content').html(function(i, current) {
  return current.replace(re, '<a href="$1" title="">$1</a>');
});
like image 61
pimvdb Avatar answered Feb 12 '26 15:02

pimvdb



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!