如何将字符串分成n个字符的段?

如标题所示,我有一个字符串,我想分成n个字符的段。


例如:


var str = 'abcdefghijkl';

经过一些魔法n=3,它将变成


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

有没有办法做到这一点?


胡说叔叔
浏览 1047回答 3
3回答

蓝山帝景

var str = 'abcdefghijkl';console.log(str.match(/.{1,3}/g));注意:使用{1,3}而不是仅{3}包括其余部分,该长度不是3的倍数,例如:console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]还有一些细微之处:如果您的字符串可能包含换行符(您希望将其视为一个字符而不是拆分字符串),则.不会捕获这些换行符。使用/[\s\S]{1,3}/代替。(感谢@Mike)。如果您的字符串为空,则当您期望一个空数组时match()将返回null。通过附加来防止这种情况|| []。因此,您可能最终得到:var str = 'abcdef \t\r\nghijkl';var parts = str.match(/[\s\S]{1,3}/g) || [];console.log(parts);console.log(''.match(/[\s\S]{1,3}/g) || []);

慕神8447489

如果您不想使用正则表达式...var chunks = [];for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {&nbsp; &nbsp; chunks.push(str.substring(i, i + 3));}...否则正则表达式解决方案就很好了:)

温温酱

以先前对该问题的答案为基础;以下函数将分割字符串(str)n个数字(size)。function chunk(str, size) {&nbsp; &nbsp; return str.match(new RegExp('.{1,' + size + '}', 'g'));}演示版(function() {&nbsp; function chunk(str, size) {&nbsp; &nbsp; return str.match(new RegExp('.{1,' + size + '}', 'g'));&nbsp; }&nbsp;&nbsp;&nbsp; var str = 'HELLO WORLD';&nbsp; println('Simple binary representation:');&nbsp; println(chunk(textToBin(str), 8).join('\n'));&nbsp; println('\nNow for something crazy:');&nbsp; println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join('&nbsp; '));&nbsp;&nbsp;&nbsp; // Utiliy functions, you can ignore these.&nbsp; function textToBin(text) { return textToBase(text, 2, 8); }&nbsp; function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); }&nbsp; function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); }&nbsp; function print(text) { document.getElementById('out').innerHTML += (text || ''); }&nbsp; function println(text) { print((text || '') + '\n'); }&nbsp; function repeat(chr, n) { return new Array(n + 1).join(chr); }&nbsp; function textToBase(text, radix, n) {&nbsp; &nbsp; return text.split('').reduce(function(result, chr) {&nbsp; &nbsp; &nbsp; return result + pad(chr.charCodeAt(0).toString(radix), n, '0');&nbsp; &nbsp; }, '');&nbsp; }&nbsp; function roundUp(numToRound, multiple) {&nbsp;&nbsp; &nbsp; if (multiple === 0) return numToRound;&nbsp; &nbsp; var remainder = numToRound % multiple;&nbsp; &nbsp; return remainder === 0 ? numToRound : numToRound + multiple - remainder;&nbsp; }}());#out {&nbsp; white-space: pre;&nbsp; font-size: 0.8em;}<div id="out"></div>
打开App,查看更多内容
随时随地看视频慕课网APP