How To Split String Into Substrings Of N Characters Using JavaScript

Split String into Substrings of N characters using JavaScript

This article can help you learn about how to split string into substrings of N characters using JavaScript. Follow this article to learn more about it with the explanation and examples below.

Split String Into Substrings Of N Characters Using JavaScript

These are some solutions that can help you achieve this. You can use the for loop and substring() or slice() method to do that. Another more practical solution is using the match() method built in the string object.

Use the for loop and substring() method

The substring() method returns a substring of the current string by the beginning index and ending index.

Syntax:

string.substring(start,end)

Parameters:

  • string: The current string
  • start: The beginning index
  • end: The ending index

Return value: A string.

In this solution, you iterate over the string for every N character. And then, you will push the substring of the current string to an array. The result you expect will be stored in this array.

Look at the example below to learn more about this solution.

function splitStringByNCharacters(string, n){
  const array = []

  for (let i = 0 ; i < string.length; i+=n) {
    array.push(string.substring(i, i+n));
  }

  return array
}

const str = 'LearnShareIT'
console.log(splitStringByNCharacters(str,3))

Output

[ 'Lea', 'rnS', 'har', 'eIT' ]

Use the slice() method

The usage of this solution is quietly the same as the first solution. You can reread it to learn more about how this solution operates. You can learn about the syntax of the slice() method in my previous tutorial here.

Look at the example below.

function splitStringByNCharacters(string, n){
  const array = []

  for (let i = 0 ; i < string.length; i+=n) {
    array.push(string.slice(i, i+n));
  }

  return array
}

const str = 'LearnShareIT'
console.log(splitStringByNCharacters(str,3))

Output

[ 'Lea', 'rnS', 'har', 'eIT' ]

Use the match() method

The match() method returns an array that matches a string with a regular expression.

Syntax:

string.match(pattern)

Parameters:

  • pattern: A regular expression.

Return value: An array.

Look at the example below to learn more about this solution.

var str = 'LearnShareIT'

// Let's try this solution when N = 3
var result = str.match(/.{1,3}/g) || [];

console.log(result)

Output

[ 'Lea', 'rnS', 'har', 'eIT' ]

Summary

These are some solutions that can help you split string into substrings of N characters using JavaScript. To do that, you can use the substring() method, slice() method, or match() method built into the string object. Choose the solution that is the most suitable for you. We hope this tutorial is helpful to you. Thanks!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *