javascript need to do a right trim javascript need to do a right trim javascript javascript

javascript need to do a right trim


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


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


There are no trim, ltrim, or rtrim functions in Javascript. Many libraries provide them, but generally they will look something like:

str.replace(/~*$/, '');

For right trims, the following is generally faster than a regex because of how regex deals with end characters in most browsers:

function rtrim(str, ch){    for (i = str.length - 1; i >= 0; i--)    {        if (ch != str.charAt(i))        {            str = str.substring(0, i + 1);            break;        }    }     return str;}