RTrim in jQuery RTrim in jQuery jquery jquery

RTrim in jQuery


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


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

string1.replace(/~+$/g,"");


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 requestingvar 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.