Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript need to do a right trim

In javascript, how to I do a right trim?

I have the following:

    var s1 = "this is a test~";

     var s = s1.rtrim('~') 

but was not successful

like image 942
Nate Pet Avatar asked Nov 15 '11 19:11

Nate Pet


4 Answers

Use a RegExp. Don't forget to escape special characters.

s1 = s1.replace(/~+$/, ''); //$ marks the end of a string
                            // ~+$ means: all ~ characters at the end of a string
like image 110
Rob W Avatar answered Oct 10 '22 20:10

Rob W


You can modify the String prototype if you like. Modifying the String prototype is generally frowned upon, but I personally prefer this method, as it makes the code cleaner IMHO.

String.prototype.rtrim = function(s) { 
    return this.replace(new RegExp(s + "*$"),''); 
};

Then call...

var s1 = "this is a test~";
var s = s1.rtrim('~');
alert(s); 
like image 21
JP Richardson Avatar answered Oct 10 '22 18:10

JP Richardson


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.trim();      // result = 'jav'
var r2 = mystring.rtrim();     // result = '   jav'
var r3 = mystring.rtrim(' v'); // result = '   ja'
var r4 = mystring.ltrim();     // result = 'jav '
like image 4
Javid Avatar answered Oct 10 '22 18:10

Javid


A solution using a regular expression:

"hi there~".replace(/~*$/, "")
like image 3
wutz Avatar answered Oct 10 '22 18:10

wutz