0

I have a regex in the server side that checks if the url is valid:

http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

This check is enough for me.

I want to make the same test in the client side.

So I created this jsfiddle:

http://jsfiddle.net/alonshmiel/LZf7H/1830/

I can't make the regex to be recognized:

var regex = /http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?/i;

Any help appreciated!

3 Answers 3

1

You need to escape forward slashes / as it will be considered as premature end of regular expression pattern for javascript.

var regex = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/i;

Examples:

regex.test("http://test.com")
=> true

regex.test("http://www.test.com")
=> true

regex.test("http://abc.test.com")
=> true
Sign up to request clarification or add additional context in comments.

1 Comment

the '?' in the sixth character doesnt say that http and https are not important? I dont understand why I got false for: www.google.com
1

You need to escape all the forward slashes.

> var regex = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/i;
> regex.test("http://myweb.com/api/v1/customer")
true

5 Comments

this is already there.Please check before posting same answers
@vks don't ask me like this. 2 or 4 sec differences is not a matter. I added some words but you posted only the regex.
@Blender right!!!!but i do delete my answers if i find d same posted before.Anywaz looks like that's not d policy anymore
@AvinashRaj and why do you think so?
@nu11p01n73R its not about reputation...its about decluttering SO
0
/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/

Try this.Escape the /.See demo.

https://regex101.com/r/vN3sH3/37

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.