TulsaNewbie
TulsaNewbie

Reputation: 401

Javascript - how to replace spaces across an entire array

I have an array of small strings, but I received that data from outside the program, so I have no idea how the data is formatted. Most specifically, I encounter a lot of situations where I have extraneous white space before and after each string.

Problem is, I have a big array. While I could do something like this:

for (var z = 0; z < myArray.length; z++) {
  myArray[z] = myArray[z].replace(/(^\s+|\s+$)/g,'');
}

or

myArray.forEach(function(part, index) {
  this[index] = this[index].replace(/(^\s+|\s+$)/g,'');
}, myArray);

I'm wondering what would be a better way, or are these pretty much the best? Is there a batch function to do that?

Upvotes: 0

Views: 1106

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

Two suggestions:

  • Rather than replace, on any even vaguely-modern browser I'd use trim, which removes whitespace from the beginning and end of the string. trim was added in ES5 (2009).
  • Unless the array is in the millions of entries, I'd probably use map, but your for loop is just fine. map creates a new array based on the result of a callback function.

Here's both suggestions combined:

myArray = myArray.map(str => str.trim());
// or ES5:
myArray = myArray.map(function(str) { return str.trim(); });

But if you don't want to create a new array, your for with trim is just fine, though you could cache myArray.length to avoid re-retrieving it on every iteration:

for (var i = 0, len = myArray.length; i < len; ++i) {
    myArray[i] = myArray[i].trim();
}

(I'd probably use let instead of var if you're targeting modern environments, so i and len are local to the loop. Modern engines optimize that well now, where they didn't always early on.)

Upvotes: 2

Related Questions