Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces at beginning of each array element

I've had to split() a large string into an array, whatever way it worked I'm now left with a space before each element.

For example:

var array = [" hello"," goodbye"," no"];

How can I get rid of this?

Split code as requested:

var depots = v.innerHTML.split(',');
like image 310
notAChance Avatar asked Jan 20 '16 15:01

notAChance


2 Answers

You can use .map and .trim

var array = [" hello"," goodbye"," no"];
array = array.map(function (el) {
  return el.trim();
});
console.log(array);

if you use ES2015, you can do it shorter, with arrow function

array = array.map(el => el.trim());
like image 165
Oleksandr T. Avatar answered Oct 19 '22 23:10

Oleksandr T.


Don't use Array#map() to change each element in the array, when you can remove the spaces from the string itself when splitting it by a delimiter.

Use String#trim() with String#split() with RegEx

str.trim().split(/\s*,\s*/)

The regex \s*,\s* will match comma surrounded by any number(including zero) of spaces.

Live Demo:

var regex = /\s*,\s*/;

document.getElementById('textbox').addEventListener('keyup', function() {
  document.getElementById('result').innerHTML = JSON.stringify(this.value.trim().split(regex));
});
<input type="text" id="textbox" />
<pre id="result"></pre>

trim() will remove the leading and trailing spaces from the string and split with the RegEx ,\s* will split the string by comma followed by any number of spaces.

The same results can also be achieved using the negated RegEx with String#match with global flag.

str.match(/[^,\s]+/g)

Why map() should not be used?

Using map in this case requires extra overheads. First, split the string by , and then iterate over each of the element of the array and remove the leading and trailing spaces using trim and then updating the array. This is bit slower than using the split with above RegEx.

like image 36
Tushar Avatar answered Oct 20 '22 00:10

Tushar