Jquery Replace while Looping LI

<div class="intro"><h2 class="heading">Info</h2>
    <ul class="cons" style="text-align: left;">
       <li>Song : Oviman</li>
       <li>Drama : Best Friend 3</li>
       <li>Vocal, Tune &amp; Lyrics : Tanveer Evan</li>
       <li>Music Composition : Piran Khan</li>
       <li>Director : Probir Roy Chowdhuy</li>
    </ul>
</div>

Trying to make every this after ‘:’ a link. like ‘Best Friend 3’ is a hole link. but it creates separate links for each words. And how to loop jQuery?

$('div.intro li').html($('div.intro li').html().replace(/((:|)[^\s]+[\w])/g, '<a href="$1" target="_blank">$1</a>'));

3 thoughts on “Jquery Replace while Looping LI”

  1. Here are some tips for you:
    $('selector').each() <- looping through
    string.split(' : ') <- easily splitting by known separator, then you can use .join to get them together again after performing some action

    Reply
  2. A simple reprenstation for @lukasz ‘s answer.

    $(".cons li").each((index, item) => {
           var str = $(item).text();
           var replacedStr = str.replace(/((:|)[^\s]+[\w])/g, '<a href="$1" target="_blank">$1</a>');
           $(item).html(replacedStr);
        })
    
    Reply

Leave a Comment