-2

I have some HTML that is dynamically generated, so I cannot edit the HTML. The HTML looks like (1). I want it to look like (2). So basically, the string at the end of the li's should be cut and pasted into an <a> that is then wrapped around the other text. Also the trailing - should get removed then.

HTML (1)

<ul>
  <li>Jovanotti – L'ombelico Del Mondo - http://youtu.be/mMNPUw2bUhM</li>
  <li>The Police – Roxanne - http://youtu.be/3T1c7GkzRQQ</li>
</ul>

What it should look like (2)

<ul>
  <li><a href="http://youtu.be/mMNPUw2bUhM" title="">Jovanotti – L'ombelico Del Mondo</a></li>
  <li><a href="http://youtu.be/3T1c7GkzRQQ" title="">The Police – Roxanne</a></li>
</ul>

It is a different question than the ones that are already asked on SO. I do not know the contents of the "url", only that it always starts with http://youtu.be.

Here is a fiddle to play with.

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239

2 Answers2

2

Loop through the elements, use .split to break up the string by ' - ' then pop off the last element (the url) and .join the rest of the string back together with ' - ' between the elements.

$('ul li').each(function () {
    var li = $(this),
        parts = li.text().split(' - ');
    li.html('<a href="' + parts.pop() + '">' + parts.join(' - ') + '</a>');
});

http://jsfiddle.net/rustyjeans/89whD/

Rusty Jeans
  • 1,426
  • 9
  • 10
0

I'd use a combination of .wrapInner() and .each():

$('ul li').wrapInner('<a>').find('a').each(function(i,el) {
    var arrCont = $(el).text().split(/\s*-\s*http/),
        strText = arrCont[0],
        strUrl = "http"+arrCont[1];
    $(el).attr('href',strUrl).attr('title','').text(strText);
});

http://jsfiddle.net/mblase75/Ax8QU/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180