[英]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.