Javascript regular expression: remove first and last slash

Viewed 84939

I have these strings in javascript:

/banking/bonifici/italia
/banking/bonifici/italia/

and I would like to remove the first and last slash if it's exists.

I tried ^\/(.+)\/?$ but it doesn't work.

Reading some post in stackoverflow I found that php has trim function and I could use his javascript translation (http://phpjs.org/functions/trim:566) but I would prefer a "simple" regular expression.

6 Answers

One liner, no regex, handles multiple occurences

const trimSlashes = str => str.split('/').filter(v => v !== '').join('/');

console.log(trimSlashes('/some/path/foo/bar///')); // "some/path/foo/bar"

you can check with str.startsWith and str.endsWith then substr if exist

  var str= "/aaa/bbb/";
  var str= str.startsWith('/') ? str.substr(1) : str;
  var str= str.endsWith('/') ? str.substr(0,str.length - 1) : str;

or you can write custom function

trimSlashes('/aaa/bbb/');

function trimSlashes(str){
  str= str.startsWith('/') ? str.substr(1) : str;
  str= str.endsWith('/') ? str.substr(0,str.length - 1) : str;
  return str;
}
Related