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會返回單個值,但是在這種情況下,單個值恰好是一個數組,當我們傳遞每個字元時,會將其附加到該數組的最後一項。當數組中的最後一項到達目標長度后,我們附加一個新的數組項。

作者:
...