javascript 使用javascript从字符串中提取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17851934/
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 09:51:56  来源:igfitidea点击:

Extract numbers from a string using javascript

javascriptjquerystringmatchextract

提问by FLuttenb

I'd like to extract the numbers from the following string via javascript/jquery:

我想通过 javascript/jquery 从以下字符串中提取数字:

"ch2sl4"

problem is that the string could also look like this:

问题是字符串也可能如下所示:

"ch10sl4"

or this

或这个

"ch2sl10"

I'd like to store the 2 numbers in 2 variables. Is there any way to use matchso it extracts the numbers before and after "sl"? Would matcheven be the correct function to do the extraction?

我想将 2 个数字存储在 2 个变量中。有什么方法可以使用match它来提取前后的数字"sl"吗?会match甚至是正确的函数来进行提取?

Thx

谢谢

回答by georg

Yes, matchis the way to go:

是的,match是要走的路:

var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);

回答by Elias Van Ootegem

If the string is always going to look like this: "ch[num1]sl[num2]", you can easily get the numbers without a regex like so:

如果字符串总是看起来像这样:"ch[num1]sl[num2]",你可以很容易地得到没有正则表达式的数字,如下所示:

var numbers = str.substr(2).split('sl');
//chop off leading ch---/\   /\-- use sl to split the string into 2 parts.

In the case of "ch2sl4", numberswill look like this: ["2", "4"], coerce them to numbers like so: var num1 = +(numbers[0]), or numbers.map(function(a){ return +(a);}.

"ch2sl4"的情况下,numbers将如下所示:["2", "4"],将它们强制为数字,如下所示:var num1 = +(numbers[0])numbers.map(function(a){ return +(a);}

If the string parts are variable, this does it all in one fell swoop:

如果字符串部分是可变的,这将一举完成:

var str = 'ch2fsl4';
var numbers = str.match(/[0-9]+/g).map(function(n)
{//just coerce to numbers
    return +(n);
});
console.log(numbers);//[2,4]

回答by Mark Walters

As an alternative just to show how things can be achieved in many different ways

作为一种替代方法,只是为了展示如何以多种不同的方式实现目标

var str = "ch2sl10";
var num1 = +(str.split("sl")[0].match(/\d+/));
var num2 = +(str.split("sl")[1].match(/\d+/));

回答by sharad-garg

Try below code

试试下面的代码

var tz = "GMT-7";
var tzOff = tz.replace( /[^+-\d.]/g, '');
alert(parseInt(tzOff));