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

例如:

var str = 'abcdefghijkl';

当n=3时,它会变成

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

有办法做到这一点吗?


当前回答

基于之前对这个问题的回答;下面的函数将分割一个字符串(str) n-number (size)的字符。

function chunk(str, size) {
    return str.match(new RegExp('.{1,' + size + '}', 'g'));
}

Demo

(function() { function chunk(str, size) { return str.match(new RegExp('.{1,' + size + '}', 'g')); } var str = 'HELLO WORLD'; println('Simple binary representation:'); println(chunk(textToBin(str), 8).join('\n')); println('\nNow for something crazy:'); println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join(' ')); // Utiliy functions, you can ignore these. function textToBin(text) { return textToBase(text, 2, 8); } function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); } function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); } function print(text) { document.getElementById('out').innerHTML += (text || ''); } function println(text) { print((text || '') + '\n'); } function repeat(chr, n) { return new Array(n + 1).join(chr); } function textToBase(text, radix, n) { return text.split('').reduce(function(result, chr) { return result + pad(chr.charCodeAt(0).toString(radix), n, '0'); }, ''); } function roundUp(numToRound, multiple) { if (multiple === 0) return numToRound; var remainder = numToRound % multiple; return remainder === 0 ? numToRound : numToRound + multiple - remainder; } }()); #out { white-space: pre; font-size: 0.8em; } <div id="out"></div>

其他回答

基于之前对这个问题的回答;下面的函数将分割一个字符串(str) n-number (size)的字符。

function chunk(str, size) {
    return str.match(new RegExp('.{1,' + size + '}', 'g'));
}

Demo

(function() { function chunk(str, size) { return str.match(new RegExp('.{1,' + size + '}', 'g')); } var str = 'HELLO WORLD'; println('Simple binary representation:'); println(chunk(textToBin(str), 8).join('\n')); println('\nNow for something crazy:'); println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join(' ')); // Utiliy functions, you can ignore these. function textToBin(text) { return textToBase(text, 2, 8); } function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); } function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); } function print(text) { document.getElementById('out').innerHTML += (text || ''); } function println(text) { print((text || '') + '\n'); } function repeat(chr, n) { return new Array(n + 1).join(chr); } function textToBase(text, radix, n) { return text.split('').reduce(function(result, chr) { return result + pad(chr.charCodeAt(0).toString(radix), n, '0'); }, ''); } function roundUp(numToRound, multiple) { if (multiple === 0) return numToRound; var remainder = numToRound % multiple; return remainder === 0 ? numToRound : numToRound + multiple - remainder; } }()); #out { white-space: pre; font-size: 0.8em; } <div id="out"></div>

如果你不想使用正则表达式…

var chunks = [];

for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
    chunks.push(str.substring(i, i + 3));
}

jsFiddle。

...否则正则表达式的解决方案是相当好的:)

const chunkStr = (str, n, acc) => {     
    if (str.length === 0) {
        return acc
    } else {
        acc.push(str.substring(0, n));
        return chunkStr(str.substring(n), n, acc);
    }
}
const str = 'abcdefghijkl';
const splittedString = chunkStr(str, 3, []);

干净的解决方案没有REGEX

var str = 'abcdefghijkl';
var res = str.match(/.../g)
console.log(res)

这里点的数量决定了你想在每个单词中包含多少文本。

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)