javascript - Array.map with String.trim

map passes each element of the array as parameter to the function:

[element1, e2].map(myFunction); // --> myFunction(element1); myFunction(e2)

String.prototype.trim is not a function that you pass a string to be trimmed. You call the function as a method of that string, instead:

" some string ".trim(); // "some string"

To use trim in a .map, you'll need to do something like:

[" a ", "b", " c", "d "].map(function(e){return e.trim();});

One shorter version with an arrow function:

[" a ", "b", " c", "d "].map(e => e.trim());

That's actually because Array.map() function should have a currentElement as an argument, while String.prototype.trim doesn't take any arguments, therefore we can't call it that way. So, you'll have to do it hard way:

[" a ", "b", " c", "d "].map(function(elem){
     return elem.trim();
});

Tags:

Javascript