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

例如:

var str = 'abcdefghijkl';

当n=3时,它会变成

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

有办法做到这一点吗?


当前回答

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

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);

其他回答

这里有一种不需要正则表达式或显式循环的方法,尽管它有点扩展了一行代码的定义:

const input = 'abcdefghijlkm';
    
// Change `3` to the desired split length.
const output = input.split('').reduce((s, c) => {
    let l = s.length-1; 
    (s[l] && s[l].length < 3) ? s[l] += c : s.push(c); 
    return s;
}, []);

console.log(output);  // output: [ 'abc', 'def', 'ghi', 'jlk', 'm' ]

它的工作原理是将字符串分割为单个字符的数组,然后使用array。还原遍历每个字符。通常情况下,reduce会返回一个值,但在这种情况下,这个值恰好是一个数组,当我们传递每个字符时,我们将它附加到该数组的最后一项。一旦数组中的最后一项达到目标长度,就追加一个新的数组项。

基于之前对这个问题的回答;下面的函数将分割一个字符串(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>

许多人也会因此举遗憾 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) ||[]);

如果你真的需要坚持使用.split和/或.raplace,那么使用/(?<=^(?:.{3})+)(?!$)/g

.split:

var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ]

.replace:

var replaced = str.replace( /(?<=^(?:.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl'

/(?!$)/表示在字符串结束时不停止。没有它的:

var arr = str.split( /(?<=^(?:.{3})+)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ] // is fine
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ')
// 'abc || def || ghi || jkl || ' // not fine

忽略组/(?:…)/是为了防止数组中存在重复项。没有它的:

var arr = str.split( /(?<=^(.{3})+)(?!$)/ )
// [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ] // not fine
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl' // is fine
var str = 'abcdefghijkl';
var res = str.match(/.../g)
console.log(res)

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