Reputation: 44275
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?
Upvotes: 30
Views: 72686
Reputation: 101
$('#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;
});
Upvotes: 0
Reputation: 1981
This is not regex but could solve your problem
var str = "abc/";
if(str.slice(-1) == "/"){
str = str.slice(0,-1)+ "";
}
Upvotes: 1
Reputation: 82564
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
Upvotes: 6
Reputation: 32598
var str = //something;
if(str[str.length-1] === "/") {
str = str.substring(0, str.length-1);
}
Upvotes: 2
Reputation: 348972
string = string.replace(/\/$/, "");
$
marks the end of a string. \/
is a RegExp-escaped /
. Combining both = Replace the /
at the end of a line.
Upvotes: 86