RulerNature RulerNature - 3 months ago 8
Javascript Question

How to split() a string to an array of integers

I have a string that should be executed as an array:

var q = "The, 1, 2, Fox, Jumped, 3, Over, 4";
var z = q.split(',');


If I use
split()
, it will create an array of strings:

[‘The’, '1', '2', ‘Fox’, ‘Jumped’, '3', ‘Over’, '4']


and I don’t need that. I need an array like:

[‘The’, 1, 2, ‘Fox’, ‘Jumped’, 3, ‘Over’, 4]


indicating which is a string and which is a number.

Answer

One option is using the Number constructor which returns a number or NaN:

var res = q.split(',').map(el => {
  let n = Number(el);
  return n === 0 ? n : n || el;
});

// > "The, 1, 2, Fox, Jumped, 3.33, Over, -0"
// < ["The", 1, 2, " Fox", " Jumped", 3.33, " Over", -0]

edit: If the above condition is confusing you can replace it with the following condition which was suggested by Bergi:

return isNaN(n) ? el : n;

In case that you want to trim the string elements you can also use the String.prototype.trim method:

return isNaN(n) ? el.trim() : n;