Freezer freezer
Freezer freezer

Reputation: 120

simple javascript regexp with urls

I am struggling with regExp.

I just want to parse incoming urls to my application.

Here is my current RegExp :

var regexp = new RegExp('/users','i');
"/users".test(regexp); //Should return true
"/users/".test(regexp); //should return true
"/users?variable1=xxx&variable2=yyy&variableN=zzzz".test(regexp); //Should return true
"/users/?variable1=xxx&variable2=yyy&variableN=zzzz".test(regexp); //should return true;
"/users?variable1=xxx&variable2=yyy&variableN=zzzz/10".test(regexp); //Should return false
"/users/?variable1=xxx&variable2=yyy&variableN=zzzz/10".test(regexp); //should return false;
"/users/10".test(regexp); //should return false
"/users/10/contracts".test(regexp); //Should return false
"/users/10/contracts/10".test(regexp); //Should return false
"/users/anythingElseThatIsNotAQuestionMark".test(regexp); //Should return false

Is anyone has the kindness to help me ?

Wish you a nice evening.

Upvotes: 1

Views: 51

Answers (3)

Patrick Roberts
Patrick Roberts

Reputation: 51876

/^\/users\/?(\?([^\/&=]+=[^\/&=]*&)*[^\/&=]+=[^\/&=]*)?$/i should work and also confirm that the query is valid:

var regexp = /^\/users\/?(\?([^\/&=]+=[^\/&=]*&)*[^\/&=]+=[^\/&=]*)?$/i;

function test(str) {
  document.write(str + ": ");
  document.write(regexp.test(str));
  document.write("<br/>");
}

test("/users"); //should return true
test("/users/"); //should return true
test("/users?variable1=xxx&variable2=yyy&variableN=zzzz"); //should return true
test("/users/?variable1=xxx&variable2=yyy&variableN=zzzz"); //should return true
test("/users?variable1=xxx&variable2=yyy&variableN=zzzz/10"); //should return false
test("/users/?variable1=xxx&variable2=yyy&variableN=zzzz/10"); //should return false
test("/users/10"); //should return false
test("/users/10/contracts"); //should return false
test("/users/10/contracts/10"); //should return false
test("/users/anythingElseThatIsNotAQuestionMark"); //should return false

Upvotes: 0

Johan Karlsson
Johan Karlsson

Reputation: 6476

First of all its RegExp.test(String)

Then this regex should do:

/^\/users\/?(?:\?[^\/]+)?$/i

Check it out: https://regex101.com/r/mK8dU4/1

Upvotes: 1

adeneo
adeneo

Reputation: 318182

It's the other way around regexp.test("/users")

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.

Syntax

regexObj.test(str)

MDN

Upvotes: 2

Related Questions