Alex Rivera | Logout

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

Asked 2011-11-15T19:08:07.457
58

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

2 Answers

106

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
answered 2011-11-15T19:10:41.883
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"));
answered 2011-11-15T19:13:42.143

Your Answer