Javascript参考正则表达式匹配

时间:2011-03-23 14:29:58

标签: javascript regex

我有一个可能包含0个或更多网址的字符串。我想用<a></a>中包含的网址替换字符串中的每个网址。有没有办法可以在replace()

中获得对当前匹配对象的引用

例如:

var msg = "Go to http://google.com and youtube.com";
var regex = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;

msg.replace(regex, "<a href='"+<blank>+"'></a>") // Where <blank> is a reference to the current matched url

谢谢!

1 个答案:

答案 0 :(得分:4)

是。使用regex backreferences。 (注意我添加到正则表达式的开头和结尾的括号,以使整个事物被放入匹配组中。)

var msg = "Go to http://google.com and youtube.com";
var regex = /([-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?)/gi;

msg.replace(regex, "<a href='$1'>$1</a>") // Where <blank> is a reference to the current matched url
相关问题