[javascript] How to remove the first and the last character of a string

I'm wondering how to remove the first and last character of a string in Javascript.

My url is showing /installers/ and I just want installers.

Sometimes it will be /installers/services/ and I just need installers/services.

So I can't just simply strip the slashes /.

This question is related to javascript string

The answer is


You could regex it:

"string".replace(/^\/?|\/?$/, "")
"/installers/services/".replace(/^\/?|\/?$/, "") // -> installers/services

The regex explained:
- Optional first slash: ^/?, escaped -> ^\/? (the ^ means beginning of string)
- The pipe ( | ) can be read as or
- Than the option slash at the end -> /?$, escaped -> \/?$ ( the $ means end of string)

Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash


use .replace(/.*\/(\S+)\//img,"$1")

"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

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

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

It may be nicer one to use slice like :

string.slice(1, -1)

if you need to remove the first leter of string

string.slice(1, 0)

and for remove last letter

string.slice(0, -1)

url=url.substring(1,url.Length-1);

This way you can use the directories if it is like .../.../.../... etc.


You can use substring method

s = s.substring(0, s.length - 1) //removes last character

another alternative is slice method


You can do something like that :

"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')

This regex is a common way to have the same behaviour of the trim function used in many languages.

A possible implementation of trim function is :

function trim(string, char){
    if(!char) char = ' '; //space by default
    char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
    var regex_1 = new RegExp("^" + char + "+", "g");
    var regex_2 = new RegExp(char + "+$", "g");
    return string.replace(regex_1, '').replace(regex_2, '');
}

Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///

You can also simply do :

"/installers/".substring(1, string.length-1);