JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string into substrings of N characters in JavaScript?

Using the match() method, you can split a string into segments of N characters. When you pass a regular expression /.{1, N}/g to the match() method, it returns an array whose elements will be substrings of N characters.

let str = "xyzxyzxyz";

let arr = str.match(/.{3}/g);
console.log(arr); //["xyz", "xyz", "xyz"]

In this example, N is 3 because we want substrings of 3 characters.

A pair of slash characters (/) is used to specify regular expressions.

In Regular expression, dot (.) means any single character. Global flag (g) is used to match all occurrences of the regular expression in the string.

If you are a bit scared with regular expressions and don't want to use them, you can use a for loop.

To split a string into segments of N characters using a for loop, follow the following steps:

  1. First, create an empty array that will have substrings of N characters.
  2. Use a for loop, and in each iteration, call the slice() method to extract a substring of N characters. Then, push that substring to the array created in Step 1.
let str = "xyzxyzxyz";
let arr = [];
let N = 3;

for(let index=0; index<str.length; index += N){
  arr.push(str.slice(index, index + N));
}

console.log(arr); //["xyz", "xyz", "xyz"]

Recommended Posts