The task is to implement String.prototype.trim().
The boilerplate code
function trim(str) {
// your code here
}
Initialise pointers to move inwards till they hit a whitespace
let start = 0;
let end = str.length - 1;
Trim leading whitespace
while (start <= end && /\s/.test(str[start])) {
start++;
}
\s matches all types of whitespace characters - spaces, tabs, newlines.
Trim ending whitespace
while (end >= start && /\s/.test(str[end])) {
end--;
}
Extract the trimmed string
return str.slice(start, end + 1);
The final code
function trim(str) {
// your code here
let start = 0;
let end = str.length - 1;
while(start <= end && /\s/.test(str[start])) {
start++;
}
while(end >= start && /\s/.test(str[end])) {
end--;
}
return str.slice(start, end + 1)
}
That's all folks!
Top comments (0)