JavaScript字符串每N位截取一次

目的

针对二进制流进行参数分割

简洁实现

代码

/.{1,3}/g 正则中的3 为匹配几位,可修改

var foo = "foofaafoofaafoofaafoofaafoofaa";
console.log( foo.match(/.{1,3}/g) );

效果
059a96b9b20c3d59b3e8ddbb6ffabf1

错误示范

第一种

function splitStr(str) {
  const res = []

  let count = 0
  let tmpStr = ''

  for (const c of str) {
    tmpStr += c
    count++

    if (count == 3) {
      res.push(tmpStr)
      count = 0
      tmpStr = ''
    }
  }

  tmpStr && res.push(tmpStr)

  return res
}

第二种

function fenge(str){
    let result=str.replace(/(\d)(?=(\d{3})+$)/g,"$1,");
    return result.split(',');
}
var str="001010101";
console.log(fenge(str));

第三种

function splitMsg(str){
    let allmsg = []
    try{
        while(str.length > 0){
            allmsg.push(str.substring(0,3))
            str = str.substring(3)
        }
    }catch(e){
        console.log(e)
    }
    return allmsg;
}
console.log(splitMsg("000101110"))

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×