How to remove the first and last character of a string

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

My url shows /installers/ and I just want installers .

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

Therefore, I cannot just simply remove the traits.

+80
javascript string
Nov 25 '13 at 14:54
source share
9 answers

Here you go

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

Or you can use .slice as suggested by Anka Gupta p>

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

Documentation for slice and substring .

+190
Nov 25 '13 at 14:57
source share

It might be better to use a slice like:

 string.slice(1, -1) 
+81
Aug 29 '14 at 11:20
source share

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

 url = url.replace(/^\/|\/$/g, ''); 
+8
Nov 25 '13 at 15:05
source share

You can reuse it:

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

Regular explanation:
- Optional first slash: ^/? , escaped → ^\/? ( ^ means start of line)
- The pipe (|) can be read as or
- Than a slash at the end → /?$ , Escaped → \/?$ ( $ Means the end of the line)

When combined, this will be ^/?|/$ Without escaping. Optional first slash OR optional last slash

+5
Nov 25 '13 at 14:56
source share

You can do something like this:

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

This regular expression is the usual way to have the same trim function behavior used in many languages.

Possible implementation of the trimmer function:

 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, ''); } 

All / at the beginning and at the end of the line will be deleted. It handles cases like ///installers/services///

You can also simply:

 "/installers/".substring(1, string.length-1); 
+2
Nov 25 '13 at 14:57
source share

You can use substring method

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

another alternative is the slice method

0
Nov 25 '13 at 15:00
source share

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

 "/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services "/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services 
0
Nov 25 '13 at 15:00
source share

The following regular expression will separate the first and last slashes, if they exist,

 var result = "/installers/services/".match(/[^/].*[^/]/g)[0]; 
-one
Nov 25 '13 at 15:00
source share
 url=url.substring(1,url.Length-1); 

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

-3
Nov 25 '13 at 14:58
source share



All Articles