Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript storing regex in a variable

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

like image 901
Drahcir Avatar asked Sep 15 '09 15:09

Drahcir


2 Answers

var re = new RegExp("^your regexp.*$", "gi");
like image 146
geowa4 Avatar answered Nov 12 '22 14:11

geowa4


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\-\@?^=%&\/~\+#])?/;
like image 15
Ates Goral Avatar answered Nov 12 '22 13:11

Ates Goral