取出字符串中的所有数字

方法一、遍历字符串并判断

复制代码
function getNum(str){
    var ary = [];
    var tem = "";
    for(var i=0;i<str.length;i++){
        if(str.charAt(i) >= "0" && str.charAt(i) <= "9"){
            tem += str.charAt(i)
        }else{
            if(tem){
                ary.push(tem);
                tem = "";
            }
        }
    }
    if(tem){
        ary.push(tem);
        tem = "";
    }
    return ary;
}
var str = "faw12aser9907awer788";
console.log(getNum(str));  //["12", "9907", "788"]
复制代码

方法二、正则匹配

var str = "faw12aser9907awer788";
var reg = /\d+/g;
console.log(str.match(reg));//["12", "9907", "788"]

posted on 2020-12-29 10:52  漫思  阅读(401)  评论(0编辑  收藏  举报

导航