Extract numbers from a string using javascript

送分小仙女□ 提交于 2019-11-28 12:32:19

Yes, match is the way to go:

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

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:

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", numbers will look like this: ["2", "4"], coerce them to numbers like so: var num1 = +(numbers[0]), or 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]

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

Try below code

var tz = "GMT-7";
var tzOff = tz.replace( /[^+-\d.]/g, '');
alert(parseInt(tzOff));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!