Reputation: 7971
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
Reputation: 3229
Try this:
var Arr = [ 'h78em', 'w145px', 'w13px' ]
function stringToNum(str){
return str.match(/\d+/g);
}
alert(stringToNum(Arr[0]));
Upvotes: 1
Reputation: 122906
Try:
['h78em', 'w145px', 'w13px']
.map(function(a){return ~~(a.replace(/\D/g,''));});
//=> [78, 145, 13]
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
Reputation: 81
Try it,this regex is better
parseInt('h343px'.replace(/^[a-zA-Z]+/,''),10)
Upvotes: 0
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
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