Username Formatter

Same behavior, two implementations — messy vs. clean

Before Messy Implementation
function formatUsername(input) {
  var result = "";
  if (input !== null && input !== undefined) {
    if (typeof input === "string") {
      var chars = input.split("");
      var trimmedLeft = false;
      var trimmedRight = false;
      var i = 0;
      var j = chars.length - 1;
      while (i < chars.length) {
        if (trimmedLeft === false) {
          if (chars[i] === " " || chars[i] === "\t"
            || chars[i] === "\n" || chars[i] === "\r") {
            i++;
          } else {
            trimmedLeft = true;
          }
        } else {
          break;
        }
      }
      while (j >= 0) {
        if (trimmedRight === false) {
          if (chars[j] === " " || chars[j] === "\t"
            || chars[j] === "\n" || chars[j] === "\r") {
            j--;
          } else {
            trimmedRight = true;
          }
        } else {
          break;
        }
      }
      if (i <= j) {
        var sub = chars.slice(i, j + 1);
        for (var k = 0; k < sub.length; k++) {
          var ch = sub[k];
          if (ch !== " " && ch !== "\t"
            && ch !== "\n" && ch !== "\r") {
            if (ch >= "A" && ch <= "Z") {
              result += String.fromCharCode(
                ch.charCodeAt(0) + 32
              );
            } else {
              result += ch;
            }
          } else {
            if (k > 0 && k < sub.length - 1) {
              var prev = sub[k - 1];
              var next = sub[k + 1];
              if (prev !== " " && prev !== "\t"
                && prev !== "\n" && prev !== "\r"
                && next !== " " && next !== "\t"
                && next !== "\n" && next !== "\r") {
                // skip internal whitespace
              } else {
                result += ch;
              }
            } else {
              result += ch;
            }
          }
        }
      }
    }
  }
  return result;
}
After Clean Implementation
function formatUsername(input) {
  if (typeof input !== "string") {
    return "";
  }

  return input
    .trim()
    .toLowerCase()
    .replace(/\s+/g, " ");
}

Live Demo

Messy Output

Clean Output

Enter a username to compare outputs