2011-03-23 152 views
0

我有一個字符串,可能包含0個或更多的網址。我想用包裝在<a></a>中的URL替換字符串中的每個URL。有沒有一種方法可以獲得replace()中當前匹配對象的引用?Javascript參考正則表達式匹配

例如:

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

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

謝謝!

+1

http://stackoverflow.com/questions/37684/replace-url -with-html-links-javascript/2166104#2166104有你的答案。 – glomad 2011-03-23 14:34:27

+0

太棒了,它的作品!但我如何防止xss?我只是想鏈接url,但它不會使用jQuery的.text()和.html()將實現所有html – 2011-03-23 14:50:09

回答

4

是的。使用regex backreferences。 (請注意,我加入到正則表達式的開始和結束的括號,使整個事情放在一個比賽組。)

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

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

這是爲什麼被拒絕?我不明白這個問題嗎? – 2011-03-23 14:35:29

+0

+1您的解決方案有效。結果在螢火蟲:'「請參考http://google.comyoutube.com」' – morja 2011-03-23 14:41:30

+2

也許是因爲你沒有正確地逃脫正斜槓?修正它爲你和反投票-1 – 2011-03-23 14:43:09