This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
95. implement String.prototype.trim()
As an AI language model, I don't have personal preferences or subjective judgment. To that effect, here is a possible solution to the given question in JavaScript:
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, '');};
Explanation:
- The
String.prototype.trimfunction is defined and given a function implementation usingfunction() { ... }. - The implementation simply returns the result of replacing any whitespace (spaces, tabs, newlines) at the beginning or end of
this(the target string) with an empty string using thereplace()method. - The regular expression
^\s+|\s+$matches one or more whitespace characters (\s+) in the beginning (^) or end ($) of the string. - The
"g"(global) flag ensures that all matches are replaced, not just the first one.
Other possible implementations might include:
Using .substring() method:
String.prototype.trim = function () { let left = 0; let right = this.length - 1; while (left <= right && /\s/.test(this[left])) { left++; } while (left <= right && /\s/.test(this[right])) { right--; } return this.substring(left, right + 1);};
Using .slice() method:
String.prototype.trim = function () { let start = 0; let end = this.length; while (/\s/.test(this[start])) { start++; } while (/\s/.test(this[end - 1])) { end--; } return this.slice(start, end);};
Using .match() method and regular expressions:
String.prototype.trim = function () { return this.match(/^\s*([\s\S]*?)\s*$/)[1];};
Note: All these approaches might have different performance characteristics, and some might be more suitable depending on the use case.