繁体   English   中英

javascript中的RegExp问题

[英]RegExp Problem in javascript

我想在文本中找到每个url,并用标签( <a href="...">...</a> )将其包装起来。

var src = "bla blaaa blaaaaaa 1  http://yahoo.com  text something about and. http://www.google.com";
var match = /http:\/\/([a-z0-9.-]+)/.exec(src); //this only can one matched
// result: ["http://yahoo.com", "yahoo.com"]

但是我需要包装所有链接。

您可以使用/g (全局)来匹配所有出现的事件和反向引用,如下所示:

var src = "bla blaaa blaaaaaa 1  http://yahoo.com  text something about and. http://www.google.com";
var match = src.replace(/http:\/\/([a-z0-9.-]+)/g, '<a href="$1">$1</a>');

您可以在这里进行测试

var res = src.replace(/(http:\/\/([a-z0-9.-]+))/g, '<a href="$1">$2</a>');

输出:

bla blaaa blaaaaaa 1 <a href="http://yahoo.com">yahoo.com</a> text something about and. <a href="http://www.google.com">www.google.com</a>

不知道那是意图,而是我能想到的。 如果您还想保留链接文本中的http://前缀,请使用<a href="$1">$1</a>代替。

(与此同时,尼克·克雷弗(Nick Craver)提供了答案介绍了g修饰符。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM