Search code examples
javascriptone-liner

Is there a one-liner to convert '1234567' into ['1234', '567', '', '']?


I need to convert a string into an array with 4 elements, each element has maximum of 4 characters.

  • "1234567812345678" -> ["1234", "5678", "1234", "5678"]
  • "12345678123" -> ["1234", "5678", "123", ""]
  • "" -> ["", "", "", ""]

The reason I want it to be a one-liner is that I need to put it into vue template string so it needs to be an expression other than a series of statements.

I don't want to create a dedicated function to just convert a single parameter to another form.

I managed to split the string into an array but I don't know how to fill in empty slots with '', here's a simplified snippet:

const creditcard = '12345678123';

// need a one liner
const groups = creditcard.split(/(?<=^(?:.{4})+)/);

console.log(groups);


Solution

  • You could pad the string to minimum 16 characters with spaces, then trim the results

    const creditcard = '12345678123';
    
    // need a one liner
    const groups = creditcard.padEnd(16, ' ').split(/(?<=^(?:.{4})+)/).map(v => v.trim());
    
    console.log(groups);