Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression: remove first and last slash

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.

like image 933
CorPao Avatar asked Oct 01 '10 15:10

CorPao


People also ask

How to remove first and last slash from url in JavaScript?

return theString. replace(/^\/|\/$/g, ''); "Replace all ( /.../g ) leading slash ( ^\/ ) or ( | ) trailing slash ( \/$ ) with an empty string."

How do I get rid of trailing slash?

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.

How do I remove the first and last character from a string in node JS?

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.


2 Answers

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

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

like image 103
kennytm Avatar answered Sep 20 '22 17:09

kennytm


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
like image 41
Daniel Vandersluis Avatar answered Sep 21 '22 17:09

Daniel Vandersluis