使用javascript从字符串中提取数字 [英] Extract numbers from a string using javascript

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

问题描述

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

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

"ch2sl4"

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

problem is that the string could also look like this:

"ch10sl4"

或者

"ch2sl10"

我想将2个数字存储在2个变量中。
有没有办法使用匹配所以它提取sl之前和之后的数字? 匹配甚至是正确的提取函数吗?

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

Thx

推荐答案

是的,匹配是要走的路:

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

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

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