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
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() .
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.
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.
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.
One shorter version with an arrow function:
[" a ", "b", " c", "d "].map(e => e.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