views:

51

answers:

2

What is wrong with the following regular expression, which works in many online JavaScript regular expression testers (and RegEx Buddy), yet doesn't work in my application?

It is intended to replace URLs with a Hyperlink. The Javascript is found in a javascript file.

var fixed = text.replace(/\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]/ig, "<a href='$&' target='blank'>$&</a>");

Chrome, for example, complains that & is not valid (as does IE8). Is there some way to escape the ampersand (or whatever else is wrong), without resorting to the RegEx object?

A: 

This works for me in Chrome

var fixed = text.replace(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/igm, "<a href='$1' target='blank'>$1</a>");
Matt
+1  A: 

Those testers let you input the regex in its raw form, but when you use it in source code you have to write it in the form of a string literal or (as is the case here) a regex literal. JavaScript uses forward-slashes for its regex-literal delimiters, so you have to escape any slashes in the regex itself to avoid confusing the interpreter.

Once you escape the slashes it should stop complaining about the ampersand. That was most likely caused by the malformed regex literal.

I recognize that regex, having used it myself the other day; you got it from RegexBuddy's Library, didn't you? If you had used RB's "Use" feature to create a JS-compatible regex, it would have escaped the slashes for you.

Alan Moore
I actually got it from the book, Regular Expressions Cookbook. The author created RegexBuddy.
WPCoder
The unescaped /'s were the problem. I was so fixated on the error message that I hadn't thought to look through the rest of the expression -- especially since I had pulled it from a book ... :) (And I'm still a bit baffled by the UX of RegExBuddy, and didn't notice the "Use" tab).
WPCoder