tags:

views:

32

answers:

3

Lets say my HTML looks like this:

<p>12345, 23, 64229, 359</p>

This paragraph can have hundreds of values seperated by comma. It can also be empty.

I wanna make these values into links. The first value should link to "http://www.example.com/?id=12345" The second value to "http://www.example.com/?id=23" ..and so on.

What would be the best way to do this?

+1  A: 

Try it out: http://jsfiddle.net/uJRb6/

var nums = $('p').text().split(/\s*,\s*/);
var tags = '';

    $.each(nums,function(i,val) {
        tags += '<a href=http://www.example.com/?id=' + val + '>' + val + '</a><br>'
    });
$('body').append(tags);​

If you're concerned about the security of the content, you could do this:

var nums = $('p').text().split(/\s*,\s*/);
var tags = [];

    $.each(nums,function(i,val) {
        tags.push($('<a>',{text:val + ' ', href:'http://www.example.com/?id=' + val}));
    });
$(tags).appendTo('body');
patrick dw
+1  A: 

you don't need jQuery for this, you can mostly do this with pure javascript:

vals = $('p').html().split(',');
for(var i in vals) {
  tags += '<a href=http://www.example.com/?id=' + val + '>link</a><br>'
}
$('body').append(tags)
GSto
Not to be difficult, but aside from the string appending, this *is* mostly jQuery :)
Nick Craver
`for/in` over an Array is not a good idea. You should use a `for` loop.
patrick dw
+2  A: 

You can use a regex .replace(), something like this:

​$("p").html(function(i, h) {
  return h.replace(/\d+/g, function(m) { return "http://www.example.com/?id=" + m; });
});​​

You can test it out here, or to make them clickable links:

$("p").html(function(i, h) {
  return h.replace(/\d+/g, function(m) { 
     return "<a href='http://www.example.com/?id="+m+"'&gt;"+m+"&lt;/a&gt;"; 
  });
});​

You can give it a try here.

Nick Craver