JavaScript String – How to Trim Specific Characters from the End

javascriptstringtrim

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

Best Answer

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