Run details:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:94.0) Gecko/20100101 Firefox/94.0
Firefox 94
Mac OS X 10.15
Desktop
3 years ago
Test name Executions per second
Regex Trim 75229.6 Ops/sec
Index Trim 1217.8 Ops/sec
Boolean Filter Trim 33609.3 Ops/sec
Spread Trim 1209.1 Ops/sec
Substring Trim 25610.1 Ops/sec
Slice Trim 26697.0 Ops/sec
Script Preparation code:
x
 
var TestString = '+'.repeat(200) + '='.repeat(20000) + '+'.repeat(200);
function regexTrim(str, what) {
  const chars = [...(what ? what : '\0\t\n\v\r ')].map((c) => ([']', '^', '\\', '-'].includes(c) ? '\\' + c : c)).join('');
  
  return str.replace(new RegExp('^[' + chars + ']+|[' + chars + ']+$', 'gu'), '');
}
function indexTrim(str, what) {
  let end, start;
  
  const chars = [...str];
  const charsToTrim = [...(what ? what : '\0\t\n\v\r ')];
  
  start = 0;
  end = chars.length;
  while (start < end && charsToTrim.includes(chars[start])) {
    ++start;
  }
  while (end > start && charsToTrim.includes(chars[end - 1])) {
    --end;
  }
  return (start > 0 || end < chars.length) ? chars.slice(start, end).join('') : str.slice();
}
function booleanTrim(str, what) {
  let result;
  
  const chars = what ? what : '\0\t\n\v\r ';
  
  result = str;
  for (const c of chars) {
    result = result.split(c).filter(Boolean).join(c);
  }
  
  return result;
}
function spreadTrim(str, what) {
  const chars = [...str];
  const charsToTrim = [...(what ? what : '\0\t\n\v\r ')];
  const end = chars.reverse().findIndex((c) => !charsToTrim.includes(c));
  const start = chars.reverse().findIndex((c) => !charsToTrim.includes(c));
  
  return chars.slice(start, chars.length - end).join('');
}
function substringTrim(str, what) {
  const chars = what ? what : '\0\t\n\v\r ';
  
  while (chars.includes(String.fromCodePoint(str.codePointAt(0)))) {
    str = str.substring(1);
  }
  while (chars.includes(String.fromCodePoint(str.codePointAt(str.length - 1)))) {
    str = str.substring(0, str.length - 1);
  }
  return str;
}
function sliceTrim(str, what) {
  const chars = what ? what : '\0\t\n\v\r ';
  
  while (chars.includes(String.fromCodePoint(str.codePointAt(0)))) {
    str = str.slice(1);
  }
  while (chars.includes(String.fromCodePoint(str.codePointAt(str.length - 1)))) {
    str = str.slice(0, -1);
  }
  return str;
}
Tests:
  • Regex Trim

     
    regexTrim(TestString, '+');
  • Index Trim

     
    indexTrim(TestString, '+')
  • Boolean Filter Trim

     
    booleanTrim(TestString, '+')
  • Spread Trim

     
    spreadTrim(TestString, '+')
  • Substring Trim

     
    substringTrim(TestString, '+')
  • Slice Trim

     
    sliceTrim(TestString, '+')