Skip to the solution
MediumDSAAsked in 20246 min read

Custom String.prototype.trim polyfill

1.4k views

The problem

Problem, as an interviewer would state it: "Implement String.prototype.myTrim from scratch — removing leading AND trailing whitespace, matching real native trim's own complete, documented definition of whitespace (spaces, tabs, newlines, and other Unicode whitespace characters), while preserving any internal whitespace."

Examples:

Code
"  hello world  ".myTrim(); // "hello world"

Clarifying questions expected:

  • Does "whitespace" for this purpose genuinely need to include tabs and newlines, not just plain spaces?
  • Should INTERNAL whitespace (between words) be genuinely preserved, only the LEADING and TRAILING whitespace removed?
  • Should this correctly coerce a non-string this (via String(this)), matching real, generic string-method behavior?

Code / implementation expected: Yes — real, direct proof matching real native trim across spaces, tabs, and newlines, confirming internal whitespace is genuinely preserved.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the trim polyfill matches real native trim, confirming internal whitespace is genuinely preserved while only leading/trailing whitespace is removed

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 77 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

DOM offset absolute coordinate

Continue