javascript - Javascript - 如何将字符串拆分为n个字符的段?

我有一个字符串,我想拆分成n个字符的段。

例如:


var str = 'abcdefghijkl';



在使用n=3之后,它变成


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



有什么方法可以做到?

时间: 作者:


var str = 'abcdefghijkl';


console.log(str.match(/.{1,3}/g));

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

  • 如果字符串可能包含换行符(要计算为字符,而不是拆分字符串),就.将不会捕获这些行,使用/[sS]{1,3}/代替,(感谢@Mike)
  • 如果字符串为空,那么当需要空数组时,match()将返回null,通过附加|| []来防止这个问题


var str = 'abcdef trnghijkl';


var parts = str.match(/[sS]{1,3}/g) || [];


console.log(parts);



console.log(''.match(/[sS]{1,3}/g) || []);

作者:

如果不想使用正则表达式。


var chunks = [];



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


 chunks.push(str.substring(i, i + 3));


}



jsFiddle。

作者:

下面的函数将拆分一个字符串(str)n个数字(size)个字符。


function chunk(str, size) {


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


}



演示


(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>

作者:

function chunk(er){


return er.match(/.{1,75}/g).join('n');


}



作者:

我的解决方案(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);



cheers!

作者:

每隔n个字符插入一个字符串:


export const intersperseString = (n: number, intersperseWith: string, str: string): string => {



 let ret = str.slice(0,n), remaining = str;



 while (remaining) {


 let v = remaining.slice(0, n);


 remaining = remaining.slice(v.length);


 ret += intersperseWith + v;


 }



 return ret;



};



像这样使用上面的代码:


console.log(splitString(3,'|', 'aagaegeage'));



我们得到:

aag|aag|aeg|eag|e

执行相同的操作,但是push到一个数组:


export const sperseString = (n: number, str: string): Array<string> => {



 let ret = [], remaining = str;



 while (remaining) {


 let v = remaining.slice(0, n);


 remaining = remaining.slice(v.length);


 ret.push(v);


 }



 return ret;



};



然后运行它:


console.log(sperseString(5, 'foobarbaztruck'));



我们得到:

['fooba','rbazt','ruck']

作者:

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, []);



没有正规表达式的干净解决方案

作者:

使用.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' ] // I don't know why is not [ 'abc', 'def', 'ghi', 'jkl' , '' ], comment?


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




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



作者:


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迭代每个字符,通常reduce会返回单个值,但是在这种情况下,单个值恰好是一个数组,当我们传递每个字符时,会将其附加到该数组的最后一项。当数组中的最后一项到达目标长度后,我们附加一个新的数组项。

作者:
...