开发者

jQuery - Separate text into strings

Lets say my HTML looks like this开发者_Go百科:

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

This paragraph can have hundreds of values separated 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?


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+"'>"+m+"</a>"; 
  });
});​

You can give it a try here.


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)


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜