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?
trim()trim()andlTrim()for trimming white space from start and end of string only, otherwise stick to your regex if you need to trim inside the string as well. in terms of optimization, the fastest you'll get is with awhileloop(slightly faster than a for loop) working backwards with a decrementing counter until 0, otherwise you can also usemapinstead of foreach. either way though, if you have something working, stick with it, if it becomes a problem for performance on the main thread, offload it to a worker process (whether in node.js or in browser, you have options)trimdoes both sides, in JavaScript it'strimStartandtrimEnd(there's also the older non-standardtrimLeftandtrimRightwhich are officially aliases in JavaScript engines on web browsers). (JS doesn't havelTrim.)