2011-03-23 8 views
0

私は0個以上のURLを含む文字列を持っています。文字列の各URLを<a></a>にラップされた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

+0

素晴らしい、それは動作します!しかし、私はどのようにxssを防ぐのですか?私はURLをリンクするだけですが、jqueryの.text()で動作しませんし、.html()はすべてのHTMLを実装します –

答えて

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

なぜこれが投票されましたか?私はその質問を理解できませんでしたか? –

+0

+1あなたのソリューションは機能します。ファイヤーバグの結果: '' http://google.comyoutube.com '' – morja

+2

スラッシュを適切にエスケープしなかったためでしょうか?あなたのためにそれを修正し、反対投票 - 1 –