Home > Enterprise >  Splitting a String into an Array not working?
Splitting a String into an Array not working?

Time:12-06

I'm trying to split a string at every 5th character as objects in array, but for some reason it just returns null.

I tried using the match function on the string, but no luck.

const aStr = "abackabaseabateabayaabbeyabbotabetsabhorabideabodeabortaboutaboveabuseabutsabyssachedachesacidsacingackeeacornacresacridactedactinactoracuteadageadaptaddedadderaddleadeptadieuadiosaditsadmanadminadmitadobeadoboadoptadoreadornadultadzesaegisaeonsaerieaffixafireafootaforeafteragainagapeagateagaveagentaggroagileagingaglowagonyagoraagreeaheadaholdaidedaideraidesailedaimedaimeraioliairedaislealarmalbumalderalephalertalgaealgalaliasalibialienalignalikealivealkydalkylallayalleyallotallowalloyallylaloesaloftalohaalonealongaloofaloudalphaaltaralteraltosalumsamassamazeamberambitambleambosamendamideamineaminoamissamityamnioamongamourampedampleamplyamuseanchoangelangerangleangryangstanimaanimeanionaniseankleannasannexannoyannulanodeanoleanticantisantsyanvilaortaapaceapartaphidapneaappleapplyapronapsesapteraptlyaquasarborardorarealareasarecaarenaargonargotargueargusariasarilsarisearmedarmoraromaarosearrayarrowarsesarsonartsyasanaascotashenashesasideaskedaskeraskewaspenaspicassayassesassetasterastirasuraatlasatmanatollatomsatoneatopyatticaudioauditaugeraughtaugurauntsauntyauralaurasautosauxinavailaversavertavianavoidavowsawaitawakeawardawareawashawfulawokeaxelsaxialaxilsaxingaxiomaxionaxlesaxonsazideazoleazure";
const aArr = aStr.match(/.{1, 5}/g) ?? [];

CodePudding user response:

You can use a loop and slice groups of 5 characters at a time, pushing the string slice into the array every iteration:

const str = 'abackabaseabateabayaabbeyabbotabetsabhorabideabodeabortaboutaboveabuseabutsabyssachedachesacidsacingackeeacornacresacridactedactinactoracuteadageadaptaddedadderaddleadeptadieuadiosaditsadmanadminadmitadobeadoboadoptadoreadornadultadzesaegisaeonsaerieaffixafireafootaforeafteragainagapeagateagaveagentaggroagileagingaglowagonyagoraagreeaheadaholdaidedaideraidesailedaimedaimeraioliairedaislealarmalbumalderalephalertalgaealgalaliasalibialienalignalikealivealkydalkylallayalleyallotallowalloyallylaloesaloftalohaalonealongaloofaloudalphaaltaralteraltosalumsamassamazeamberambitambleambosamendamideamineaminoamissamityamnioamongamourampedampleamplyamuseanchoangelangerangleangryangstanimaanimeanionaniseankleannasannexannoyannulanodeanoleanticantisantsyanvilaortaapaceapartaphidapneaappleapplyapronapsesapteraptlyaquasarborardorarealareasarecaarenaargonargotargueargusariasarilsarisearmedarmoraromaarosearrayarrowarsesarsonartsyasanaascotashenashesasideaskedaskeraskewaspenaspicassayassesassetasterastirasuraatlasatmanatollatomsatoneatopyatticaudioauditaugeraughtaugurauntsauntyauralaurasautosauxinavailaversavertavianavoidavowsawaitawakeawardawareawashawfulawokeaxelsaxialaxilsaxingaxiomaxionaxlesaxonsazideazoleazure';
const arr = [];

for (let i = 0; i < str.length; i  = 5) {
  arr.push(str.slice(i, i   5));
}

console.log(arr.length, arr); // 243 ['aback', ..., 'azure']

If the string's length cannot be divided by 5 without a remainder, the final string element in the array will have a length that is less than 5.

CodePudding user response:

Adjust your regex to aStr.match(/.{5}/g). This will return you the required array

CodePudding user response:

You must remove space at regex.

const aArr = aStr.match(/.{1,5}/g) ?? [];

  • Related