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

1
  • What's with the &? That doesn't quite work with the character class. Also, no need to escape the + or . inside the character class. Commented Sep 15, 2009 at 15:14

3 Answers 3

35
var re = new RegExp("^your regexp.*$", "gi");
Sign up to request clarification or add additional context in comments.

1 Comment

And then to use: yourString.match(re).
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\-\@?^=%&\/~\+#])?/;

Comments

2

You can escape the slash inside your regex:

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

(you already did so with the first two slashes...)

Comments

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.