Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将字符串中的数字转换为链接_Javascript_Jquery_Replace - Fatal编程技术网

Javascript 将字符串中的数字转换为链接

Javascript 将字符串中的数字转换为链接,javascript,jquery,replace,Javascript,Jquery,Replace,我需要你的帮助。 我正在尝试创建一个用户脚本,用于查找大于x位的数字,并将它们转换为链接。 链接的结构是这样的 到目前为止,我已经设法找到了链接,将它们放在一个数组中,但我一直试图用链接替换文本中的数字 $("p").each(function(){ var string = $(this).text(); var getNum = string.match(/(\d+)/g); for(i=0; i<getNum.length; i++){ i

我需要你的帮助。 我正在尝试创建一个用户脚本,用于查找大于x位的数字,并将它们转换为链接。 链接的结构是这样的

到目前为止,我已经设法找到了链接,将它们放在一个数组中,但我一直试图用链接替换文本中的数字

$("p").each(function(){

    var string = $(this).text();
    var getNum = string.match(/(\d+)/g);

    for(i=0; i<getNum.length; i++){
        if(getNum[i].length >= 5){



            //for testing the array
            $('#result').append(i+" : " + getNum[i]+" ");
        };
    }

});
有什么建议/解决方案吗


听起来你好像在尝试内联替换它们,我已经更新了你的fiddle,但你所需要的只是正则表达式,并立即用链接替换它:

$("p").each(function(){
    $(this).html($(this).html().replace(/(\d{5,})/g, '<a href="http://domain.com/$1">$1</a>'));
});
编辑:

由于@DavidThomas,jquery库的使用效率更高

$('p').html(function(index, html){
    return html.replace(/(\d+)/g, '<a href="http://domain.com/$1">$1</a>');
})

我相信这就是你想要的。需要将中的文本替换为带有''的新标记; }; } $this.htmlstring; }; 这是1234号123455测试11234343323

数组=更简单的解决方案

document.body.innerHTML=document.body.innerHTML.replace/\b\d{5,}\b/g;
这是一个1234数字123455测试11234343323

那么,您想要这个:?还是出于某种原因需要“结果”一段?你的问题并不能完全解释你想要什么或者这个元素的用途。是的,我可以从所有的反对票中看出。感谢您至少评论了一些不清楚的地方:公认的答案是我想要传达的。他是完美的!奇怪的是,这就是我一直在思考和尝试的。。不知道我做错了什么。。哦,好吧。非常感谢。您可以使用manWhy not:$'p'.htmlfunction index,html{return html.replace/regex/,replacement;}来避免重复调用$this和使用html?@DavidThomas,因为我专注于给定的内容并保留了原始循环。你的方式更干净、更高效,我已经把它添加到我的答案中。非常好!你能解释一下/\b\d{5,}\b/g吗?@user3426703\b表示整个单词的单词边界,\d{5,}表示最小长度为5的数字,g表示第一次出现后不停止