Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript split string to array of int

I have a string that's on the page and from which I want an array of int.

<div id="TheData">2,3,0,43,23,53</div> 

I'm writing this:

var ArrayData = ($('#TheData').html()).split(','); 

However, ArrayData becomes an array of strings. How can I get an array of ints? Note that some of the elements in the HTML can be equal to 0.

Thanks.

like image 367
frenchie Avatar asked Nov 22 '11 19:11

frenchie


People also ask

How do you split an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

var ArrayData = $('#TheData').html().split(',').map( Number ); 

Add Array.prototype.map() to older browsers with the code from MDN.


You can use jQuery's $.map() in the same manner, though it won't work with $.prototype.map().

var ArrayData = $.map( $('#TheData').html().split(','), Number ); 
like image 185
RightSaidFred Avatar answered Sep 24 '22 14:09

RightSaidFred