2

I have the ajax urls in the pattern shown below ;

http://example.com/v1/components/compId

http://example.com/v1/machine/machineId

http://example.com/v1/graph/startTime=value?endtime=value

http://example.com/v1/graph/startDate=value?enddate=value?startTime=value?endtime=value

I want to validate the above url-patterns in javascript.I have used some regex like

var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; 

but its returning true for http://example.com/v1/machine/machineId and

http://example.com/v1 (this should return false).

please let me know is there any way to validate the above urls

Thanks in advance..

1
  • did the answer work or are you still struggling with it? Commented Apr 21, 2014 at 19:53

1 Answer 1

1

javalearner, if http://www.example.com/v1 is a fixed part of your match, it looks to me like you could go with something as simple as

if (/http:\/\/example\.com\/v1\/[^\/]+\/[\w=?]+/.test(subject)) { // Successful match } else { // Match attempt failed } 

However, if that part is not fixed, you could go with something like

if (/(?:https?|ftp):\/\/[a-z\d-]+\.[a-z]{2,6}\/[^\/]+\/[^\/]+\/[\w=?]+/.test(subject)) { // Successful match } else { // Match attempt failed } 

Note that the {2,6} allows for matching of top level domains up to 6 letters (com, net etc) but you want to make that longer or unrestricted.

If there are other special characters you may have at the end of your string, you can add them inside the bracket in the [\w=?]+ component.

Also, if you want it to be case insensitive, you'll want to insert a i between the final / delimiter and .test like so: /i.test

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.