0

I am trying to find a regex that will work for validating URLs. I found this guy:

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

Which worked pretty well when I tested it using regexpal, but when I actually plug it into my javascript it fails to match. Fiddle here.

I am testing against this URL:

http://s3.amazonaws.com/SomeShow/Podcasts/HouroneofWhatever234.mp3

Can anyone see why it would match in regexpal, but not when I try to use it in my javascript?

1 Answer 1

4

Use a regex literal:

/^(http|ftp|https):\/\/[\w-]+...$/

(you also have to escape the slashes to prevent the them to be interpreted as ending regex terminal symbol)

If you use a string, you have to escape every backslash, because the backslash is the escape characters in strings as well.

new RegExp("^(http|ftp|https)://[\\w-]+...$")

In your current expression, "[\w-]+" will turn to [w]+ because \w is not a valid escape sequence in strings.


See: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions#Creating_a_Regular_Expression

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

3 Comments

And escape every forward slash.
because I will get an unexpected token error otherwise? jsfiddle.net/tJhFN/2
Yeah, fixed... it's a bit late here ;)

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.