js 正则表达式获取字符串中每个字符出现的次数

function getStrLen(str) {
    var charObj = {};
    str.replace(/\S/g, function(l){charObj[l] = (isNaN(charObj[l]) ? 1 : charObj[l] + 1);});
    return charObj;
}
getStrLen("1232145654") // {1: 2, 2: 2, 3: 1, 4: 2, 5: 2, 6: 1}

 

posted @ 2022-12-30 17:15  李健威  阅读(444)  评论(0)    收藏  举报