Search code examples
javascriptstringtrim

How to trim specific characters from the end of the JavaScript string?


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

Solution

  • 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