30

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?

Joe
  • 80,724
  • 18
  • 127
  • 145
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348

7 Answers7

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
2
var str = "example/";
str = str.replace(/\/$/, '');
daiscog
  • 11,441
  • 6
  • 50
  • 62
2
var t = "example/";
t.replace(/\/$/, ""));
Larsenal
  • 49,878
  • 43
  • 152
  • 220
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
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