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?
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.).
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.
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.
Or this can be solved with arrow functions:
x.map(s => s.trim());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With