Alex Rivera | Logout

Javascript storing regex in a variable

Asked 2009-09-15T15:08:20.703
9

I have this line of code in javascript

var re = (http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

Usually I encapsulate the regex syntax with the / characters but since they are found within the regex it screws up the encapsulation. Is there another way how I can store it inside the variable?

The current slashes that seem like escape characters are part of the regex, since I am using this in c# aswell and works perfectly

Edit
Report

1 Answer

16

One way is to escape all occurances of / in your regex as \/, like you're already partially doing:

var re = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?/;
answered 2009-09-15T15:14:13.373

Your Answer