0

How to split strings at specific intervals to arrays in Javascript?

For example: split this string into 4 characters (including space and characters)

this is an example should be split,numbers(123),space,characters also included

to

this ------> 1st array
 is  ------> 2nd array
 an  ------> 3rd array
exam ------> 4th array
ple  ------> 5th array
shou ------> 6th array     ............ etc till.....
..ed ------> last array

4 Answers 4

1

Try this:

    var foo = "this is an example should be split,numbers(123),space,characters also included"; 
    var arr = [];
    for (var i = 0; i < foo.length; i++) {
        if (i % 4 == 0 && i != 0)
            arr.push(foo.substring(i - 4, i));
        if (i == foo.length - 1)
            arr.push(foo.substring(i - (i % 4), i+1));          
    }
    document.write(arr);
    console.log(arr);
Sign up to request clarification or add additional context in comments.

1 Comment

i am new to javascript, so can you please edit the code so that we can see the output in window (using document.write())
1

Here's a function that splits your string into chunks of whatever size you want:

function splitN(s, n) {
    var output = [];
    for (var i = 0; i < s.length; i+=4) {
        output.push(s.substr(i, 4));
    }
    return(output);
}

You can see it work here: http://jsfiddle.net/jfriend00/JvabJ/

Comments

0

Change the "4"'s to "n"'s in the above code:

function splitN(s, n) {
    var output = [];
    for (var i = 0; i < s.length; i+=n) {
        output.push(s.substr(i, n));
    }
    return(output);
}

Comments

0

You can use match along with a regex:

console.log("this is an example should be split,numbers(123),space,characters also included".match(/.{1,4}/g)); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.