0

I would like to parse a string that contains numbers, to make each number clickable with a hyperlink that contains that number, for a number of cells in a table.

I have a string that could be formated something like: 12345, 54321, 13542 or 12345 and 54321 and 13542 or even Number12345 etc. There is no limit to the amount of numbers within the cell.

I would like for these numbers to be hyperlinks something like:

http://www.example.com/example?q=12345
http://www.example.com/example?q=54321
http://www.example.com/example?q=13542

I'd be grateful to hear about any way in JS/JQuery to do this.

Thanks!

4

2 回答 2

3

只要您的表格单元格中只有文本,这应该可以解决问题:

$(document).ready(function(){
    $("#myTable td").each(function(){
        var text = $(this).html();
        text = text.replace(/(\d+)/g, '<a href="http://example.com/$1">$1</a>');
        $(this).html(text);
    });
});

我在 JsFiddle 上设置了一个示例来测试它:http: //jsfiddle.net/EzfzU/

于 2013-04-29T13:55:30.700 回答
0

我会尝试以下功能,这是对先前答案的修改

$(document).ready(function(){
    $("#myTable td").each(function(){
        var text = $(this).html();
        text = text.replace(/(\d+)/gm, '<a href="http://example.com/$1">$1</a>');
        $(this).html(text);
    });
});

请注意以下差异:

  • \d+ 以贪婪匹配捕获任何数字(确保至少存在 1 个数字)
  • /gm 修饰符以确保即使带有换行符的字符串也匹配其内容
于 2013-04-29T13:59:08.197 回答