Doug Fir
Doug Fir

Reputation: 21212

Apply two regex rules in match()

var url = document.referrer;
var a=document.createElement('a');
a.href=url;
var path = a.pathname;

Let's say path is this:

/cat-dog-fish/

I want to remove leading and trailing slashes, if they exist, else do nothing.

I can do this (removes trailing slash):

a.pathname.replace(/\/$/,'')

Or this (removes leading slash)

a.pathname.replace(/^\//,'')

But how do I remove both at once, in a oner, if they exist?

Upvotes: 0

Views: 63

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

A regex literal like /^\/|\/$/g can be used to replace with empty string, or you may use /^\/([^]*)\// (match /, then any 0+ chars up to the last / capturing what is in-between the slashes) to replace with $1:

var s = "/cat-dog-fish/";
console.log(s.replace(/^\/|\/$/g, ''));
console.log(s.replace(/^\/([^]*)\/$/, '$1'));

Note:

  • ^\/ - matches the start of string and a / right there
  • | - means OR
  • \/$ - matches a / at the end of string
  • ([^]*) - is a capturing group (...) that captures 0 or more (*) any characters as [^] means not nothing.

Upvotes: 2

Saloo
Saloo

Reputation: 816

var a="/cat-dog-fish/";

var d = a.replace(new RegExp("(^\/|\/$)",'g'),'');

console.log(d);

    a.pathname.replace(new RegExp("(^\/|\/$)",'g'),'');

Upvotes: 1

Related Questions