P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

Regex to remove last / if it exists as the last character in the string

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

Answers (7)

Metafr
Metafr

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

Chandrakant
Chandrakant

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

Joe
Joe

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

Larsenal
Larsenal

Reputation: 51146

var t = "example/";
t.replace(/\/$/, ""));

Upvotes: 2

daiscog
daiscog

Reputation: 12057

var str = "example/";
str = str.replace(/\/$/, '');

Upvotes: 2

Dennis
Dennis

Reputation: 32598

var str = //something;
if(str[str.length-1] === "/") {
    str = str.substring(0, str.length-1);
}

Upvotes: 2

Rob W
Rob W

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

Related Questions