How to remove the first and the last character of a string
Solution 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.
Solution 2:
It may be nicer one to use slice
like :
string.slice(1, -1)
Solution 3:
I don't think jQuery has anything to do with this. Anyway, try the following :
url = url.replace(/^\/|\/$/g, '');
Solution 4:
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".
Solution 5:
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);