在JavaScript中将字符串拆分为多个部分
我们需要编写一个JavaScript函数,该函数接受一个字符串和一个数字n(以使n精确地划分字符串的长度),并且我们需要返回一个长度为n的字符串数组,其中包含n个相等的部分。
示例
为此的代码将是-
const str = 'we will be splitting this string into parts';
const num = 6;
const divideEqual = (str, num) => {
const len = str.length / num;
const creds = str.split("").reduce((acc, val) => {
let { res, currInd } = acc;
if(!res[currInd] || res[currInd].length < len){
res[currInd] = (res[currInd] || "") + val;
}else{
res[++currInd] = val;
};
return { res, currInd };
}, {
res: [],
currInd: 0
});
return creds.res;
};
console.log(divideEqual(str, num));输出结果
控制台中的输出-
[ 'we will ', 'be split', 'ting thi', 's string', ' into pa', 'rts' ]
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短