const trim = (string) => {
let strArr = string.split("");
let trimedStr = [];
strArr.forEach((item) => {
if (item !== " ") {
trimedStr.push(item);
}
});
return trimedStr.join("");
};
console.log("trim", trim("Hello world nice world"));
// output => trim: Helloworldniceworld
Problem Explanation
Let's break down the problem in simple terms:
You have a piece of code that defines a function called trim. The purpose of this function is to remove all the spaces from a given string. In other words, if you pass a sentence with spaces into this function, it will return the same sentence but with all the spaces removed.
How the Function Works:
Splitting the String: The function starts by taking the input string
(e.g., "Hello world nice world")
and splits it into an array of individual characters. For example, "Hello world" becomes['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']..
.Filtering Out Spaces: The function then goes through each character in the array. If the character is not a space
(' ')
, it adds it to a new array calledtrimedStr
. If it is a space, it simply skips it.Rejoining the Characters: After filtering out the spaces, the function takes the remaining characters and joins them back together into a single string without any spaces.
Returning the Result: Finally, the function returns the new string that has no spaces.
Top comments (4)
Filtering out spaces is not what
trim
does. It will remove leading and trailing whitespace.There is also an issue with the way you're splitting the string. Try your code with a string containing emojis - it will break. A better, although still not perfect version of your code would be:
Thanks for the explanation, appreciated your response π
A better route overall is probably using
replace
on the string though.Cool, got it, thanks, keep looking my other posts and future post too, and do suggest the different approaches πβοΈ