0

I have a string that may contain 0 or more urls. I want to replace each url in the string with that url wrapped in <a></a>. Is there a way I can get a reference to the current matched object inside a replace()?

For example:

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

Thanks!

Mark
  • 39,169
  • 11
  • 42
  • 48
  • 1
    http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript/2166104#2166104 has your answer. – glomad Mar 23 '11 at 14:34
  • great, it works! but I how do i prevent xss? I just want to linkify urls, but it wont work with jquery's .text(), and .html() would implement ALL html – Mark Mar 23 '11 at 14:50

1 Answers1

4

Yes. Use regex backreferences. (Notice the parentheses I added to the beginning and end of the regular expression, to make the entire thing be put in a match group.)

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
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69