Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Array.map with String.trim

Tags:

javascript

Why doesn't the following work? (Chrome, so no issues with Arrays.map missing)

[" a ", "b", " c", "d "].map(String.prototype.trim)

TypeError: String.prototype.trim called on null or undefined
like image 781
prasopes Avatar asked Aug 06 '14 13:08

prasopes


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. To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd() .

How do you trim and split a string?

To split a string and trim the surrounding spaces: Call the split() method on the string. Call the map() method to iterate over the array.

How do I trim a string in TypeScript?

In TypeScript, the trim() method is used to remove whitespace from both sides of a string. This method is also available in JavaScript because it is a subset of TypeScript.

What is map in JavaScript with example?

Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted.


1 Answers

One shorter version with an arrow function:

[" a ", "b", " c", "d "].map(e => e.trim());
like image 197
greuze Avatar answered Oct 11 '22 11:10

greuze