Trim specific character from a string

fubo picture fubo · Oct 2, 2014 · Viewed 168k times · Source

What's the JavaScript equivalent to this C# Method:

var x = "|f|oo||"; 
var y = x.Trim('|'); //  "f|oo"

C# trims the selected character only at the beginning and end of the string!

Answer

leaf picture leaf · Sep 11, 2015

One line is enough:

var x = '|f|oo||';
var y = x.replace(/^\|+|\|+$/g, '');
document.write(x + '<br />' + y);

^\|+   beginning of the string, pipe, one or more times
|      or
\|+$   pipe, one or more times, end of the string

A general solution:

function trim (s, c) {
  if (c === "]") c = "\\]";
  if (c === "\\") c = "\\\\";
  return s.replace(new RegExp(
    "^[" + c + "]+|[" + c + "]+$", "g"
  ), "");
}

chars = ".|]\\";
for (c of chars) {
  s = c + "foo" + c + c + "oo" + c + c + c;
  console.log(s, "->", trim(s, c));
}