56

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('~');
2

10 Answers 10

105

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
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to trim whitespace do s1 = s1.replace(/\s+$/, '')
7

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

4 Comments

It's frowned upon for a reason. Don't do this!
@Evert Why is that?
@Javid You're polluting the global namespace, which can cause collisions with others and break scripts that expect a standard library. What's the big drawback of doing: rtrim(foo, s) vs foo.rtrim(s) ?
This was written 9 years ago. I would never recommend modifying the prototype of String today.
7

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

2 Comments

Your function is wrong, in case of str contains only ch chars
Well, spotted! It's also over 10 years old at this point. :-D I edited it with a fix. Thanks!
5

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 mystring = '   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 '

Comments

3

A solution using a regular expression:

"hi there~".replace(/~*$/, "")

Comments

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

1 Comment

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
0
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

2 Comments

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.
Oh, shoot, though question was asking how to trim a specific character, not whitespace
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'

Comments

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"
"///// = "
"/ = "

Comments

-1

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

_.trimEnd('this is a test~', '~')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.