Adam Jenkins
Adam Jenkins

Reputation: 55772

Silly regexp URL matching

So I want this:

/services/auth/token

To match this:

http://localhost:3000/services/auth/token/ trailing / optional

but not this:

http://localhost:3000/services/auth/token/refresh

I'm normally better at this stuff but I'm kind of sleepy. Help SO!!!

EDIT:

Thanks SO, but I should've said want to do this with variables, which is what's confusing me. Forgot to add a JS tag, my apologies.

const myPath = '/services/auth/token';
const pathToCheck = 'http://localhost:3000/services/auth/token/';

pathToCheck.match(myPath); // doesn't work, also matches against refresh

Upvotes: 0

Views: 56

Answers (3)

anubhava
anubhava

Reputation: 785651

You can avoid regex and use endsWith with 2 strings (one without trailing / and one with):

const myPath = '/services/auth/token';
const pathToCheck = 'http://localhost:3000/services/auth/token/';

var matched = false;

// without trailinbg slash
matched = pathToCheck.endsWith(myPath);
console.log(matched);

// with trailinbg slash
matched = pathToCheck.endsWith(myPath + '/');
console.log(matched);


IE doesn’t support some of the String methods such as String.endsWith. To make this method work in IE use:

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

Reference

Upvotes: 1

Alvin S. Lee
Alvin S. Lee

Reputation: 5182

You can try the following:

regex = /services\/auth\/token\/?$/

This ensures your string must end at the optional slash following token.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522244

A simple negative lookahead should work here:

\/services\/auth\/token\/(?!refresh\b).*

The above pattern says to match /services/auth/token/, so long as what follows is not refresh.

Demo

If instead you have a whitelist of accepted paths which may follow, then we can use those in place of using a negative lookahead.

Upvotes: 0

Related Questions