URL regex does not work in javascript

I am trying to use John Gruber's URL regex in Javascript but NetBeans keeps telling me there is a syntax error and illegal errors:

 var patt = "/(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])
|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]
{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|
(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|
(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:
'".,<>?«»“”‘’]))/";

Anyone know how to solve this?

Answers:

Answer

As others have said, it's the double quote. But alternatively, you can just write the regexp as a literal in javascript (but then you need to escape the forward slashes in lines 1 and 3 instead).

var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;

I also moved the case-insensitive modifier to the end. Just because. (edit: Well, not just "because" - see Alan Moore's comment below)

Note: Whether you use a literal or a string, it has to be on 1 line.

Answer

put the whole expression in one line, and remove the quotes at the start and end so it looks like this var patt = /the-long-patttern/;, netbeans will still complain, but the browsers won't and thats what matters.

Answer

You should write it like this in NetBeans:

      "(?i)\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]"
      + "+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))"
      + "+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.