views:

58

answers:

3

Hi, I have these strings:

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

and I would like to remove - with javascript - first slash 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" regexp.

Many thanks.

+6  A: 
return theString.replace(/^\/|\/$/g, '');

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

KennyTM
A: 

It would be better if you would avoid using regular expresssions here. Simply check if the first caracter is a slash and remove it if it is. Same thing at the end of the string.

It will be easier to write, and easier to debug later on. I'm not saying regex are not usefull but if you use too much of them, when they can be avoided, your code will become unreadable.

Silence
That's exactly what KennyTM's regex does. I don't think it can get much easier than that.
NullUserException
+1  A: 

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:

Daniel Vandersluis
That's a good kis point of view (Keep It Simple)
Aif
There's a real reason to use regexp here, and it is to keep the code concise and readable.
Razor