String.prototype.trimLoading saved progress…

String.prototype.trim

String.prototype.trim removes whitespace from both ends of a string and returns the result, leaving the middle untouched. It's what you run on user input before validating it, so that " yes " and "yes" are treated the same.

Implement stringTrim(str). Strip every whitespace character from the start and the end — spaces, tabs, newlines, and Unicode whitespace like the non-breaking space — but keep any whitespace that sits between non-whitespace characters.

Signature

function stringTrim(str) {
  // returns str with leading and trailing whitespace removed;
  // interior whitespace is preserved.
}

Examples

stringTrim('  hello  ');        // 'hello'
stringTrim('\t\n  hi  \n');     // 'hi'  — tabs and newlines count too
stringTrim('  hello   world  '); // 'hello   world' — interior spaces kept
stringTrim('   \t  ');           // ''  — all-whitespace trims to empty

Notes

  • Both ends only — remove leading and trailing whitespace; never touch whitespace inside the string.
  • All whitespace, not just spaces — tabs (\t), newlines (\n), carriage returns (\r), and Unicode whitespace (e.g. the non-breaking space  ) all count.
  • All-whitespace input — a string that's nothing but whitespace trims to ''.
  • Empty string — returns '' unchanged.
  • RelatedtrimStart removes only the leading side, trimEnd only the trailing side. This question does both.
Loading editor…