Lou*_*dec 4 javascript numbers extract
有人知道从Javascript中的字符串中提取数字的方法吗?
例如:1个香蕉+ 1个菠萝+ 3个橙子
我的目的是将结果放在数组或JSON或其他内容中
结果:[1,1,3]
小智 12
var result= "1 banana + 1 pineapple + 3 oranges";
result.match(/[0-9]+/g)
Run Code Online (Sandbox Code Playgroud)
使用String.prototype.match()和parseInt():
let s = "1 banana + 1 pineapple + 3 oranges";
let result = s.match(/\d+/g).map(n => parseInt(n));
console.log(result);Run Code Online (Sandbox Code Playgroud)
使用此正则表达式
var str="1 banana + 1 pineapple + 3 oranges",mats=[];
str.match(/\d+/g).forEach(function(i,j){mats[j]=parseInt(i);});
console.log(mats);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9396 次 |
| 最近记录: |