0

Possible Duplicate:
Regex to remove last / if it exists as the last character in the string
Javascript: How to remove characters from end of string?

In Javascript how can I check if a string contains \ (backslash) at the end of it, and if so remove it? Looking for a regex solution.

Appreciate your time and help.

Community
  • 1
  • 1
user1052933
  • 191
  • 2
  • 4
  • 8
  • 1
    Please show more research efforts. Googling for "remove last character of string javascript regex" shows a lot results, including http://stackoverflow.com/q/7602301/427545 – Lekensteyn May 29 '12 at 19:31

2 Answers2

4
if (myString.match(/\\$/)) { 
  myString = myString.substring(0, myString.length - 1);
}

The Regex '\$' Will match an escaped character '\' followed by the end of line. If this is a match, it runs the substring method to get everything but the last character.

As pointed out, in this case this can be simplified to:

myString = myString.replace(/\\$/, "");

(Thankyou @Lekensteyn for pointing it out)

I've left both answers up so one can see the methodology if removing the match is no longer the goal.

Aren
  • 54,668
  • 9
  • 68
  • 101
-1

I'd suggest:

var string = 'abcd\\';
if (string.charAt(string.length - 1) == '\\'){
    // the \ is the last character, remove it
    string = string.substring(0, string.length - 1);
}

References:

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
David Thomas
  • 249,100
  • 51
  • 377
  • 410