正如标题所说,我有一个字符串,我想把它分成n个字符的片段。

例如:

var str = 'abcdefghijkl';

当n=3时,它会变成

var arr = ['abc','def','ghi','jkl'];

有办法做到这一点吗?


当前回答

str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']

其他回答

function str_split(string, length = 1) {
    if (0 >= length)
        length = 1;
    
    if (length == 1)
        return string.split('');

    var string_size = string.length;
    var result = [];

    for (let i = 0; i < string_size / length; i++)
        result[i] = string.substr(i * length, length);

    return result;
}

str_split(str, 3)

基准测试:http://jsben.ch/HkjlU(不同浏览器的结果不同)

结果(Chrome 104)

许多人也会因此举遗憾 console.log (str.match (/ . {130 / g);

注意:对于不是3倍数的字符串长度,使用{1,3}而不是{3}来包含余数,例如:

console.log (abcd .match (/ {1,3} / g));// ["abc", "d"]


还有一些微妙之处:

如果字符串可能包含换行符(希望将换行符作为字符计算,而不是分割字符串),则。不会捕获这些。使用/[\s\ s]{1,3}/代替。(谢谢@Mike)。 如果字符串为空,则match()将返回空数组。通过添加||[]来防止这种情况。

所以你可能会得到:

var str = 'abcdef \t\r\nghijkl'; var parts = str.match(/[\s\S]{1,3}/g) ||[]; 控制台.log(零件); console.log(''.match(/[\s\S]{1,3}/g) ||[]);

我的解决方案(ES6语法):

const source = "8d7f66a9273fc766cd66d1d";
const target = [];
for (
    const array = Array.from(source);
    array.length;
    target.push(array.splice(0,2).join(''), 2));

我们甚至可以这样创建一个函数:

function splitStringBySegmentLength(source, segmentLength) {
    if (!segmentLength || segmentLength < 1) throw Error('Segment length must be defined and greater than/equal to 1');
    const target = [];
    for (
        const array = Array.from(source);
        array.length;
        target.push(array.splice(0,segmentLength).join('')));
    return target;
}

然后你可以以一种可重用的方式轻松地调用函数:

const source = "8d7f66a9273fc766cd66d1d";
const target = splitStringBySegmentLength(source, 2);

干杯

试试这个简单的代码,它会像魔法一样工作!

let letters = "abcabcabcabcabc";
// we defined our variable or the name whatever
let a = -3;
let finalArray = [];
for (let i = 0; i <= letters.length; i += 3) {
    finalArray.push(letters.slice(a, i));
  a += 3;
}
// we did the shift method cause the first element in the array will be just a string "" so we removed it
finalArray.shift();
// here the final result
console.log(finalArray);
str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']