skip to Main Content

I want to split a string every 4 characters and push them into an array. I have been trying to loop through using .substring but my loop stops at the first 4 characters.

So want to turn this string…

let list = "abcdefghijklmnop"

into this array…

[ "abcd", "efgh", "ijkl", "mnop"]

2

Answers


  1. You can achieve this by using a loop to iterate over the string and extracting substrings of 4 characters at a time.

    Here’s code to achieve your result:

    let list = "abcdefghijklmnop";
    let resultArray = [];
    
    for (let i = 0; i < list.length; i += 4) {
      let chunk = list.substring(i, i + 4);
      resultArray.push(chunk);
    }
    
    console.log(resultArray);
    

    Output:

    [ 'abcd', 'efgh', 'ijkl', 'mnop' ]
    
    Login or Signup to reply.
  2. You could take a regular expression which searches for four characters.

    const
        list = "abcdefghijklmnop",
        parts = list.match(/.{4}/g);
    
    console.log(parts);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search