【题目】 请编写一个函数,可以将一个任意长度的字符串按照指定大小进行分割,并将分割后的字符串存储在一个数组中返回。
【难度】中等
函数签名如下:
function splitString(str, size) {
// 你的代码
}
其中,str表示需要分割的字符串,size表示每个子串的大小。
例如,对于输入的字符串"abcdefg",以及size为2,函数应该返回["ab", "cd", "ef", "g"]
-------懂事的分割线-----
tips:文末有答案
--------请思考,嘿嘿!---------
【答案一】
function splitString(str, size) {
let result = [];
for (let i = 0; i < str.length; i += size) {
result.push(str.slice(i, i + size));
}
return result;
}
// 测试
console.log(splitString("abcdefg", 2));
// 输出 ["ab", "cd", "ef", "g"]
这个函数通过循环遍历输入的字符串,每次取出指定大小的子串,并存储到结果数组中,最后返回结果数组。
【答案二】
使用正则
function splitString(str, size) {
let result = str.match(new RegExp(`.{1,${size}}`, "g"));
return result || [];
}
// 测试console.log(splitString("abcdefg", 2));
// 输出 ["ab", "cd", "ef", "g"]
这个函数首先使用正则表达式构造一个匹配任意长度子串的模式,然后使用match()函数将输入的字符串按照指定的大小进行分割,最后返回结果数组。注意,如果结果数组为空,则需要返回一个空数组。