29

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
  • 77,580
  • 18
  • 124
  • 143
P.Brian.Mackey
  • 41,438
  • 63
  • 228
  • 337

7 Answers7

80
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
  • 328,606
  • 78
  • 779
  • 666
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
  • 77,580
  • 18
  • 124
  • 143
2
var str = //something;
if(str[str.length-1] === "/") {
    str = str.substring(0, str.length-1);
}
Dennis
  • 31,394
  • 10
  • 61
  • 78
2
var str = "example/";
str = str.replace(/\/$/, '');
daiscog
  • 10,302
  • 5
  • 46
  • 61
2
var t = "example/";
t.replace(/\/$/, ""));
Larsenal
  • 47,632
  • 41
  • 144
  • 213
1

This is not regex but could solve your problem

var str = "abc/";

if(str.slice(-1) == "/"){
str = str.slice(0,-1)+ "";
}
Chandrakant
  • 1,939
  • 1
  • 12
  • 32
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
  • 91
  • 8