I would like a regular expression or otherwise some method to remove the last character in a string if and only if that character is '/'. How can I do it?
Asked
Active
Viewed 6.9k times
30
-
what language are you using? javascript? php? – Jeff Sep 29 '11 at 19:18
-
6@Jeff - Javascript, its on the tags my friend. – P.Brian.Mackey Sep 29 '11 at 19:20
7 Answers
83
string = string.replace(/\/$/, "");
$
marks the end of a string. \/
is a RegExp-escaped /
. Combining both = Replace the /
at the end of a line.

Rob W
- 341,306
- 83
- 791
- 678
6
Just to give an alternative:
var str="abc/";
str.substring(0, str.length - +(str.lastIndexOf('/')==str.length-1)); // abc
var str="aabb";
str.substring(0, str.length - +(str.lastIndexOf('/')==str.length-1)); // aabb
This plays off the fact the Number(true) === 1
and Number(false) === 0

Joe
- 80,724
- 18
- 127
- 145
3
var str = //something;
if(str[str.length-1] === "/") {
str = str.substring(0, str.length-1);
}

Dennis
- 32,200
- 11
- 64
- 79
1
This is not regex but could solve your problem
var str = "abc/";
if(str.slice(-1) == "/"){
str = str.slice(0,-1)+ "";
}

Chandrakant
- 1,971
- 1
- 14
- 33
-
2Instead of `str.slice(-1) == "/"` it might be cleaner to use `str.endsWith("/")`, – Guillaume F. Sep 23 '21 at 17:52
0
$('#ssn1').keyup(function() {
var val = this.value.replace(/\D/g, '');
val = val.substr(0,9)
val = val.substr(0,3)+'-'+val.substr(3,2)+'-'+val.substr(5,4)
val = val.replace('--','').replace(/-$/g,'')
this.value = val;
});

Metafr
- 101
- 9