1

I'm trying to use this regexp from jeff Atwood's blog post on detecting links:

\(?\bhttp://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]

However, this JS code breaks and gives a SyntaxError: Unexpected token ILLEGAL

var myRe = \(?\bhttp://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|];
var myArray = myRe.exec("http://en.wikipedia.org/wiki/PC_Tools_(Central_Point_Software)");
console.log(myArray);
1
  • As an aside comment, you can reduce the size of your character classes using ranges and \w: var myRe = /\(?\bhttp:\/\/[!#%&()+-;=?-Z_a-z~|]*[-\w#%&()+\/=@|~]/; Commented Oct 23, 2013 at 3:48

2 Answers 2

3

This is because your JS is in fact invalid. This is not a valid RegExp literal:

var myRe = \(?\bhttp://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|];

A RegExp literal starts with / and similarly ends with / in JS, so you can change the code to this:

var myRe = /\(?\bhttp:\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|]/;

And it should work (you may need to turn on the console tab.) Note that because / is a literal terminal, you have to escape any / characters in your RegExp with a \ character.

Sign up to request clarification or add additional context in comments.

Comments

1

Try declaring it as a regex variable (inside //):

var myRe = /\(?\bhttp:\/\/[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]/;

And check out some documentation.

2 Comments

Please don’t use new RegExp. (e.g. you forgot to escape \b)
Yeah, I'll get rid of the dysfunctional first one. Second one's fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.