开发者

Get digits out of text in JavaScript or jQuery

How to get digits out of text in JavaScript or jQuery?

Like this one in PHP:

<?php
    $a = "2 Apples";
    $b = "3 Peach";
    echo $a + $b // It will print 5! Thanks for this stupid smartness, 2 apples + 3 peaches should be 2 apples and 3 peaches or maybe a nice jam!
?>

Now I want to do something like this with JavaScript with/without jQuery.

var a = "100$";
var b = "120$";
var ttl = 100 - Math.round( a + b );

Even开发者_开发知识库 if I used (a + b * 1) and also (a*1) + (b*1) to see if it turns it to Int, it returned NaN!


You need to parse them. parseInt() will drop the trailing non-digit characters.

var a = parseInt("100$", 10);
var b = parseInt("120$", 10);

var ttl = 100 - Math.round( a + b );

alert(ttl); // alerts -120

As @Jeremy said, this will not work for leading non-digit characters. Example:

alert(parseInt("$100", 10)); // alerts "NaN"


Try defining a function like so:

function stripToNums(str) {
    return str.replace(/\D/g, '');
}

And call that on your strings. It should strip any non-digit chars out of the string. Of course, you'll need to get a little trickier if you want to handle non-integer number values.

Here's a live demo of that: http://jsfiddle.net/Ender/QEhfR/

Note that you'll need to parse the returned strings as ints in this example, or the script will do string concatenation with the two returned values, rather than the intended mathematical addition.


Use parseInt(). It returns an integer value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜