RTrim in jQuery

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.


One option:

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

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


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,"");

Tags:

Jquery