How can I take a sting containing numbers such as
1 - 2 - 3 - 4 - 5 - 6
and convert each number into a integer?
I have tried the following, but it just returns the first integer.
var a = '1 - 2 - 3 - 4 - 5 - 6';
var b = parseInt( a.split('-') );
$('#b').append(b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='b'></div>
That is because string.split returns an array of strings.
If you want to handle each individual value returned by split
, loop over the array and parse the items as numbers while iterating.
You can then do with the parsed number as you will. (in this example, it multiplies every number by two and appends the output)
var a = '1 - 2 - 3 - 4 - 5 - 6';
var splitarray = a.split('-')
for(var i=0; i < splitarray.length; i++)
{
var valueAsInt = parseInt(splitarray[i]);
//do whatever you want with valueAsInt, like for instance
valueAsInt *= 2;
//adding the br so we can see what the individual numbers are
$('#resultDiv').append(valueAsInt + "<br />");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultDiv"></div>