有一个字符串,需要按固定长度分割,以数组形式返回。
我们用正常的函数是这样的:
function formatLongStrToArr(str,len){ var arrLength = Math.ceil(str.length / len); var tempArr = new Array(arrLength); for(var index = 0; index<arrLength; index++){ tempArr[index] = str.substr(index*len,len); } return tempArr; } console.log(formatLongStrToArr(‘全新计算架构和编程语言‘,3)); //["全新计","算架构","和编程","语言"] console.log(formatLongStrToArr(‘new计算-架构&编程-语言‘,5)); //["new计算","-架构&编","程-语言"]
但用以下正则会更轻便:
console.log(‘全新计算架构和编程语言‘.match(/.{1,3}/g)); //["全新计","语言"] console.log(‘new计算-架构&编程-语言‘.match(/.{1,5}/g)); //["new计算","程-语言"]