Remove spaces at beginning of each array element
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());
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.