47

In JavaScript, how do I trim from the right(string end)?

I have the following example:

var s1 = "this is a test~";
var s = s1.rtrim('~');
rjanjic
  • 2,640
  • 1
  • 15
  • 13
Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • Top hit on google: http://blog.stevenlevithan.com/archives/faster-trim-javascript – Tessmore Nov 15 '11 at 19:55
  • JavaScript now has `trimEnd()` and `trimStart()`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart – sideshowbarker Apr 09 '21 at 07:08
  • What browsers do support `trimEnd()` → https://caniuse.com/mdn-javascript_builtins_string_trimend – Avatar Dec 30 '21 at 19:34

10 Answers10

95

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
Rob W
  • 341,306
  • 83
  • 791
  • 678
5

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)
{
  let i = str.length;
  while (i-- && str.charAt(i) === ch);
  return str.substring(0, i + 1);
}

console.log(rtrim("moo", "x"));
console.log(rtrim("moo", "o"));
console.log(rtrim("oo", "o"));
Scott A
  • 7,745
  • 3
  • 33
  • 46
5

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); 
JP Richardson
  • 38,609
  • 36
  • 119
  • 151
4

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 '
Javid
  • 2,755
  • 2
  • 33
  • 60
3

A solution using a regular expression:

"hi there~".replace(/~*$/, "")
wutz
  • 3,204
  • 17
  • 13
1
str.trimEnd();
str.trimRight();

These are currently stage 4 proposals expected to be part of ES2019. They work in NodeJS and several browsers.

See below for more info:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
JJ McKool
  • 45
  • 4
  • Seems to be supported in all real browsers by now. Note that `trimEnd()` is the name consistent with `padEnd()`, while `trimRight()` is left as a legacy alias for compatibility with some browsers. – Klesun Apr 25 '20 at 13:34
  • 2
    Oh, shoot, though question was asking how to trim a specific character, not whitespace – Klesun Apr 25 '20 at 13:45
0

This is old, I know. But I don't see what's wrong with substr...?

function rtrim(str, length) {
  return str.substr(0, str.length - length);
}
JD Byrnes
  • 783
  • 6
  • 17
  • 1
    The only problem here is that there could be any number of characters at the end of the string... say instead of `this is test~` they happened to have `this is test~~~` or even none `this is test`. Your case does however work nicely for trimming a set number of characters from the string, regardless of what the character may be – bobkingof12vs Apr 10 '15 at 21:40
0

This removes a specified string or character from the right side of a string

function rightTrim(sourceString,searchString) 
{ 
    for(;;) 
    {
        var pos = sourceString.lastIndexOf(searchString); 
        if(pos === sourceString.length -1)
        {
            var result  = sourceString.slice(0,pos);
            sourceString = result; 
        }
        else 
        {
            break;
        }
    } 
    return sourceString;  
}

Please use like so:

rightTrim('sourcecodes.....','.'); //outputs 'sourcecodes'
rightTrim('aaabakadabraaa','a');   //outputs 'aaabakadabr'
0

My 2 cents:

function rtrim(str: string, ch: string): string
{
    var i:number = str.length - 1; 
    
    while (ch === str.charAt(i) && i >= 0) i--
    
    return str.substring(0, i + 1);
}

const tests = ["/toto/", "/toto///l/", "/toto////", "/////", "/"]

tests.forEach(test => {
    console.log(`${test} = ${rtrim(test, "/")}`)
})

Gives

"/toto/ = /toto"
"/toto///l/ = /toto///l"
"/toto//// = /toto"
"///// = "
"/ = "
Thomas Decaux
  • 21,738
  • 2
  • 113
  • 124
0

You can add lodash library. It is a JavaScript utility library, There are some trim functions. You can use:

_.trimEnd('this is a test~', '~')
cola
  • 21
  • 2