Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery convert num string to int

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>
like image 345
Sergio Avatar asked Oct 15 '25 14:10

Sergio


2 Answers

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>
like image 93
Timothy Groote Avatar answered Oct 17 '25 10:10

Timothy Groote


parseInt will convert a single string, not an array of strings.

You can use jquery $.each to parse each item and return an array of int.

(putting this into html as in the question and the snippet below doesn't really mean much as it will convert back to string for the html, but the values can be manipulated once in the array).

var a = '1 - 2 - 3 - 4 - 5 - 6';
var arr = $.each(a.split('-'), function() { return parseInt(this, 10); });

var a = '1 - 2 - 3 - 4 - 5 - 6';
var b = $.each(a.split('-'), function() { return parseInt(this, 10); });
// b is now an array of ints
$("#result").html(b.join(","))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='result'>
</div>
like image 21
freedomn-m Avatar answered Oct 17 '25 08:10

freedomn-m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!