Trim all Strings in an Array using JavaScript-Code Examples

Radu TM

Trim all Strings in an Array using JavaScript

JavaScript by Radu TM June 21, 2022

// Trim all Strings in an Array using JavaScript
const strings = ['   🌟   ', '  🌟🌟  ', ' 🌟🌟🌟 ', '🌟🌟🌟🌟'];

// Use .map() to iterate over the array, and use .trim() to remove the whitespace from each string.
const trimmedStrings = strings.map(string => string.trim());

// The trimmedStrings array should now look like this:
// ['🌟', '🌟🌟', '🌟🌟🌟', '🌟🌟🌟🌟']

0

21.271

Trim all Strings in an Array using JavaScript

JavaScript by Radu TM June 21, 2022

const array = [
  "Hello, world!",
  "  space ",
  "",
  "emoji ",
];

// Trim all strings in the array.
const trimmedArray = array.map((str) => str.trim());

// Print the results.
console.log(trimmedArray);

0

21.271

Trim all Strings in an Array using JavaScript

JavaScript by Radu TM June 21, 2022

const trimArray = (arr) => {
  return arr.map((str) => str.trim());
};

// Test
console.log(trimArray([' 🌎  ', '🌍 ', '  🌏'])); // ['🌎', '🌍', '🌏']

0

21.271

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories