Jitender
Jitender

Reputation: 7971

ParseInt() method on array

I am wondering to how to get number from an array. I have tried its give me NaN error

<script type="text/javascript">

$(function(){

var Arr = [ 'h78em', 'w145px', 'w13px' ]

alert(parseInt(Arr[0]))


})
</script>

Upvotes: 0

Views: 14161

Answers (7)

Dhanasekar Murugesan
Dhanasekar Murugesan

Reputation: 3229

Try this:

var Arr = [ 'h78em', 'w145px', 'w13px' ]

function stringToNum(str){
  return str.match(/\d+/g);

}

alert(stringToNum(Arr[0]));

http://jsfiddle.net/8WwHh/1/

Upvotes: 1

KooiInc
KooiInc

Reputation: 122906

Try:

['h78em', 'w145px', 'w13px']
 .map(function(a){return ~~(a.replace(/\D/g,''));});
 //=> [78, 145, 13]

See also

Or use a somewhat more elaborate String prototype extension:

String.prototype.intsFromString = function(combine){
 var nums = this.match(/\d{1,}/g);
 return !nums ? 0 
         : nums.length>1 ? combine ? ~~nums.join('') 
           : nums.map(function(a){return ~~a;}) 
         : ~~nums[0];
};
// usage
'abc23'.intsFromString();          //=> 23
'3abc121cde'.intsFromString();     //=> [3,121]
'3abc121cde'.intsFromString(true); //=> 3121
'abcde'.intsFromString();          //=> 0
// and ofcourse
['h78em', 'w145px', 'w13px'].map(function(a){return a.intsFromString();});
//=> [78, 145, 13]

Upvotes: 3

yao lu
yao lu

Reputation: 81

Try it,this regex is better

parseInt('h343px'.replace(/^[a-zA-Z]+/,''),10)

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16764

How about

alert(parseInt(Arr[0].replace(/[a-z_A-Z]/g,"")));

jsfiddle

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

try with

+Arr[0].replace(/\D/g, '');

Example fiddle: http://jsfiddle.net/t6yCV/

Starting + is working like parseInt() and it is necessary if you need to perform some mathematical operation with the number obtained: in fact

typeof Arr[0].replace(/\D/g,'')  // String
typeof +Arr[0].replace(/\D/g,'') // Number

Upvotes: 3

MAK
MAK

Reputation: 26586

Yet another quick and dirty solution:

alert(Arr[0].match("\\d+"));

Upvotes: 0

gabitzish
gabitzish

Reputation: 9691

You can build a function that builds the number from your string:

function stringToNum(str){
  num = 0;
  for (i = 0; i < str.length; i++) 
    if (str[i] >= '0' && str[i] <= '9') 
      num = num * 10 + parseInt(str[i]);
  return num;
}

jsFiddle : http://jsfiddle.net/8WwHh/

Upvotes: 1

Related Questions