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(',');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With