Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Apply trim function to each string in an array

Want to trim each string in an array, e.g., given

x = [' aa ', ' bb ']; 

output

['aa', 'bb'] 

My first trial is

x.map(String.prototype.trim.apply) 

It got "TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function" in chromium.

Then I tried

x.map(function(s) { return String.prototype.trim.apply(s); }); 

It works. What's the difference?

like image 450
neuront Avatar asked Oct 10 '13 11:10

neuront


People also ask

How do you trim a string in JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

How do you trim values in a string?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

How do I copy part of an array in JavaScript?

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.


1 Answers

Or this can be solved with arrow functions:

x.map(s => s.trim()); 
like image 106
Dominic Avatar answered Oct 13 '22 01:10

Dominic