49

I am having a problem with jQuery's trim. I have a string such at in jQuery:

var string1;
string1 = "one~two~";

How do I trim the trailing tilde?

John
  • 1
  • 13
  • 98
  • 177
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

7 Answers7

89

The .trim() method of jQuery refers to whitespace ..

Description: Remove the whitespace from the beginning and end of a string.


You need

string1.replace(/~+$/,'');

This will remove all trailing ~.

So one~two~~~~~ would also become one~two

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
10

Just use the javascript replace to change the last string into nothing:

string1.replace(/~+$/g,"");
Konerak
  • 39,272
  • 12
  • 98
  • 118
9

IMO this is the best way to do a right/left trim and therefore, having a full functionality for trimming (since javascript supports string.trim natively)

String.prototype.rtrim = function (s) {
    if (s == undefined)
        s = '\\s';
    return this.replace(new RegExp("[" + s + "]*$"), '');
};
String.prototype.ltrim = function (s) {
    if (s == undefined)
        s = '\\s';
    return this.replace(new RegExp("^[" + s + "]*"), '');
};

Usage example:

var str1 = '   jav ~'
var r1 = mystring.rtrim('~'); // result = '   jav ' <= what OP is requesting
var r2 = mystring.rtrim(' ~'); // result = '   jav'
var r3 = mystring.ltrim();      // result = 'jav ~'

P.S. If you are specifying a parameter for rtrim or ltrim, make sure you use a regex-compatible string. For example if you want to do a rtrim by [, you should use: somestring.rtrim('\\[') If you don't want to escape the string manually, you can do it using a regex-escape function if you will. See the answer here.

Javid
  • 2,755
  • 2
  • 33
  • 60
4

One option:

string1 = string1.substring(0,(string1.length-1));

long way around it .. and it jsut strips the last character .. not the tilde specifically..

Silvertiger
  • 1,680
  • 2
  • 19
  • 32
-1
var myStr = "One~Two~Three~Four~"     
var strLen = myStr.length;
myStr = myStr.slice(0,strLen-1);
alert (myStr);

This will delete the last character in the string. Is that what you wanted?

Nick
  • 1,262
  • 1
  • 17
  • 32
-3
string1 = string1.substring(0, string1.length - 1);

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

karim79
  • 339,989
  • 67
  • 413
  • 406
-6

You can use substring javascript method.

Try this

var string1 = "one~two~";
string1 = $.trim(string1).substring(0, string1.length -1);
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 2
    This will trim any character off the end of the input string, not only a ~ as requested. – Rylab Dec 04 '14 at 19:50