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.
return theString. replace(/^\/|\/$/g, ''); "Replace all ( /.../g ) leading slash ( ^\/ ) or ( | ) trailing slash ( \/$ ) with an empty string."
Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.
To remove the first and last characters from a string, call the slice() method, passing it 1 and -1 as parameters, e.g. str. slice(1, -1) . The slice method returns a new string containing the extracted section from the original string.
return theString.replace(/^\/|\/$/g, '');
"Replace all (/.../g
) leading slash (^\/
) or (|
) trailing slash (\/$
) with an empty string."
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:
String.substr
String.charAt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With