Javascript regex: remove first and last slash

I have these lines in javascript:

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

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

I tried ^\/(.+)\/?$ But it does not work.

Reading some post on stackoverflow. I found that php has a trim function, and I could use its javascript translation ( http://phpjs.org/functions/trim : 566), but I would prefer a β€œsimple” regular expression.

+50
javascript regex
Oct 01 '10 at 15:25
source share
4 answers
 return theString.replace(/^\/|\/$/g, ''); 

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

+117
01 Oct '10 at 15:30
source share

There is no real reason to use 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 jsFiddle action.

Literature:

+24
01 Oct 2018-10-10
source share

Just in case, if someone needs 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) 
+3
Mar 12 '16 at 18:08
source share

In case using RegExp is not an option , or you need to handle corner cases when working with URLs (for example, double / triple slashes or blank lines without complex replacements) or using additional processing, here is a less obvious, but more functional 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 filter() snippet, a function can implement more complex logic than just filtering empty strings (which is the default behavior).

A word of warning is not as fast as the other fragments here.

+1
Dec 04 '17 at 16:21
source share



All Articles