如何从字符串中获取数值? [英] how to get numeric value from string?

查看:50
本文介绍了如何从字符串中获取数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将提醒23。

alert(parseInt('23 asdf'));

但这不会提醒23但警告NaN

But this will not alert 23 but alerts NaN

alert(parseInt('asdf 23'));

如何从 'asd98'中获取数字

How can I get number from like 'asd98'?

推荐答案

您可以使用正则表达式获取第一个整数:

You can use a regex to get the first integer :

var num = parseInt(str.match(/\d+/),10)

如果你想解析任何数字(不只是一个正整数,例如asd -98.43),请使用

If you want to parse any number (not just a positive integer, for example "asd -98.43") use

var num = str.match(/-?\d+\.?\d*/)

现在假设你的字符串中有多个整数:

Now suppose you have more than one integer in your string :

var str = "a24b30c90";

然后你可以得到一个数组

Then you can get an array with

var numbers = str.match(/\d+/g).map(Number);

结果: [24,30,90]

对于有趣和影子向导,这里是一个没有正则表达式的解决方案,只包含一个整数的字符串(可以扩展为多个整数):

For the fun and for Shadow Wizard, here's a solution without regular expression for strings containing only one integer (it could be extended for multiple integers) :

var num = [].reduce.call(str,function(r,v){ return v==+v?+v+r*10:r },0);

这篇关于如何从字符串中获取数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆