Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the first and the last character of a string

People also ask

How do I remove the first and last character of a string in Excel?

In Excel 2013 and later versions, there is one more easy way to delete the first and last characters in Excel - the Flash Fill feature. In a cell adjacent to the first cell with the original data, type the desired result omitting the first or last character from the original string, and press Enter.

How do I remove the last character of a string?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How do you remove the first and last character of a string in bash?

To remove the first and last character of a string, we can use the parameter expansion syntax ${str:1:-1} in the bash shell. 1 represents the second character index (included). -1 represents the last character index (excluded). It means slicing starts from index 1 and ends before index -1 .


Here you go

var yourString = "/installers/";
var result = yourString.substring(1, yourString.length-1);

console.log(result);

Or you can use .slice as suggested by Ankit Gupta

var yourString = "/installers/services/";

var result = yourString.slice(1,-1);

console.log(result);

Documentation for the slice and substring.


It may be nicer one to use slice like :

string.slice(1, -1)

I don't think jQuery has anything to do with this. Anyway, try the following :

url = url.replace(/^\/|\/$/g, '');

If you dont always have a starting or trailing slash, you could regex it. While regexes are slower then simple replaces/slices, it has a bit more room for logic:

"/installers/services/".replace(/^\/?|\/?$/g, "") 

# /installers/services/ -> installers/services
# /installers/services -> installers/services
# installers/services/ -> installers/services

The regex explained:

  • ['start with' ^] + [Optional?] + [slash]: ^/?, escaped -> ^\/?
  • The pipe ( | ) can be read as or
  • ['ends with' $] + [Optional ?] + [slash] -> /?$, escaped -> \/?$

Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash.
Technically it isn't "optional", but "zero or one times".