How to Split a String Every N Characters in JavaScript

08/01/2021

Contents

In this article, you will learn how to split a string every N characters in JavaScript.

Splitting a string every N characters in JavaScript

In JavaScript, it is possible to split a string into smaller chunks of a fixed length, where each chunk has N characters. This can be useful for a variety of purposes, such as formatting strings or manipulating data.

Using the substring() method

The substring() method in JavaScript can be used to extract a portion of a string starting from a specified index and ending at a specified index. By iterating through the string and using the substring() method, we can split the string into smaller chunks of a fixed length.

Example

function splitString(str, n) {
  let result = [];
  for (let i = 0; i < str.length; i += n) {
    result.push(str.substring(i, i + n));
  }
  return result;
}

const str = "abcdefghij";
const n = 3;
const arr = splitString(str, n);
console.log(arr); // ["abc", "def", "ghi", "j"]

In this example, we defined a function splitString() that takes two parameters: str and n. The function iterates through the string str and extracts substrings of length n using the substring() method. The substrings are stored in an array result, which is then returned.

Using regular expressions

Regular expressions can also be used to split a string every N characters in JavaScript. We can use the match() method with a regular expression that matches substrings of length N.

Example

function splitString(str, n) {
  const regex = new RegExp(`.{1,${n}}`, "g");
  return str.match(regex);
}

const str = "abcdefghij";
const n = 3;
const arr = splitString(str, n);
console.log(arr); // ["abc", "def", "ghi", "j"]

In this example, we defined a function splitString() that takes two parameters: str and n. We created a regular expression /.{1,N}/g that matches substrings of length n, and passed it to the match() method. The match() method returns an array of substrings that match the regular expression.

Using ES6 features

In ES6, it is possible to split a string into smaller chunks using the Array.from() method and a mapping function. The Array.from() method creates an array from an iterable object, and the mapping function extracts substrings of length N from the string.

Example

function splitString(str, n) {
  return Array.from({ length: Math.ceil(str.length / n) }, (_, i) =>
    str.slice(i * n, i * n + n)
  );
}

const str = "abcdefghij";
const n = 3;
const arr = splitString(str, n);
console.log(arr); // ["abc", "def", "ghi", "j"]

In this example, we defined a function splitString() that takes two parameters: str and n. We used the Array.from() method to create an array with a length equal to the number of chunks in the string. We then used a mapping function to extract substrings of length n from the string using the slice() method.