javascript 如何从字符串中获取数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18712347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:57:27  来源:igfitidea点击:

how to get numeric value from string?

javascriptjquery

提问by Navin Rauniyar

This will alert 23.

这将提醒 23。

alert(parseInt('23 asdf'));

But this will not alert 23 but alerts NaN

但这不会提醒 23 而是提醒 NaN

alert(parseInt('asdf 23'));

How can I get number from like 'asd98'?

我怎样才能从 like 中获得号码'asd98'

回答by Denys Séguret

You can use a regex to get the first integer :

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

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

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

如果要解析任何数字(不仅仅是正整数,例如“asd -98.43”),请使用

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);

Result : [24, 30, 90]

结果 : [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);

回答by at.

parseInt('asd98'.match(/\d+/))

回答by Emil A.

function toNumeric(string) {
    return parseInt(string.replace(/\D/g, ""), 10);
}

回答by LondonAppDev

You have to use regular expression to extract the number.

您必须使用正则表达式来提取数字。

var mixedTextAndNumber= 'some56number';
var justTheNumber = parseInt(mixedTextAndNumber.match(/\d+/g));

回答by Skyline0705

var num = +('asd98'.replace(/[a-zA-Z ]/g, ""));