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
  • 11,516
  • 11
  • 87
  • 151
Nate Pet
  • 41,226
  • 116
  • 259
  • 398

7 Answers7

88

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
  • 183,160
  • 33
  • 252
  • 304
10

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

string1.replace(/~+$/g,"");
Konerak
  • 38,301
  • 12
  • 96
  • 116
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,670
  • 2
  • 30
  • 55
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,670
  • 2
  • 18
  • 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,222
  • 1
  • 16
  • 31
-3
string1 = string1.substring(0, string1.length - 1);

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

karim79
  • 334,458
  • 66
  • 409
  • 405
-6

You can use substring javascript method.

Try this

var string1 = "one~two~";
string1 = $.trim(string1).substring(0, string1.length -1);
ShankarSangoli
  • 68,720
  • 11
  • 89
  • 123
  • 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