Javascript regular expression: remove first and last slash

JavascriptRegex

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

return theString.replace(/^\/|\/$/g, '');

"Replace all (/.../g) leading slash (^\/) or (|) trailing slash (\/$) with an empty string."

Solution 2 - Javascript

There's no real reason to use a regex here, string functions will work fine:

var string = "/banking/bonifici/italia/";
if (string.charAt(0) == "/") string = string.substr(1);
if (string.charAt(string.length - 1) == "/") string = string.substr(0, string.length - 1);
// string => "banking/bonifici/italia"

See this in action on jsFiddle.

References:

Solution 3 - Javascript

In case if using RegExp is not an option, or you have to handle corner cases while working with URLs (such as double/triple slashes or empty lines without complex replacements), or utilizing additional processing, here's a less obvious, but more functional-style solution:

const urls = [
  '//some/link///to/the/resource/',
  '/root',
  '/something/else',
];

const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));

console.log(trimmedUrls);

In this snippet filter() function can implement more complex logic than just filtering empty strings (which is default behavior).

Word of warning - this is not as fast as other snippets here.

Solution 4 - Javascript

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"

Solution 5 - Javascript

Just in case that someone needs a premature optimization here...

http://jsperf.com/remove-leading-and-trailing-slashes/5

var path = '///foo/is/not/equal/to/bar///'
var count = path.length - 1
var index = 0

while (path.charCodeAt(index) === 47 && ++index);
while (path.charCodeAt(count) === 47 && --count);

path = path.slice(index, count + 1)

Solution 6 - Javascript

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCorPaoView Question on Stackoverflow
Solution 1 - JavascriptkennytmView Answer on Stackoverflow
Solution 2 - JavascriptDaniel VandersluisView Answer on Stackoverflow
Solution 3 - JavascriptDamaged OrganicView Answer on Stackoverflow
Solution 4 - JavascriptMaciej KrawczykView Answer on Stackoverflow
Solution 5 - JavascriptyckartView Answer on Stackoverflow
Solution 6 - JavascriptAkin ZemanView Answer on Stackoverflow