How to Split large string in to n-size chunks in JavaScript?


A string is an order of one or more characters that contain numbers, letters, symbols, or special characters. In JavaScript strings are immutable. i.e., once you create a string you cannot change its value.

For example, consider the following snippet here we have created a string variable and assigned a value (Tutorialspoint) to it. In the next statement, we are trying to change the contents of the string at the first index. Then we are displaying the contents of the string.

let x = 'Tutorialspoint';  
x[0] = 't';  
console.log(x); //Tutorialspoint.

On executing this code displays the string “Tutorialspoint” i.e. the value of the original string hasn’t changed.

But, you can assign a new value to an existing string −

let y = 'Tutorialspoint';  
y = 'tutorialspoint';  
cosole.log(y); //tutorialspoint.

Splitting a large String in to chunks

We need to split a Sting into n-sized chunks means we need to divide a large string into n-size sub-strings.

For example, consider a string 'helloworld' and if the value of n is 2. The output will be "he", "ll", "ow", "or", "ld".

Let’s see some input and output scenarios −

Let’s consider a scenario where we are having a string and we are splitting the string with a length of 2 characters.

Input = 'Tutorialspoint' 
Output = 'Tu', 'to', 'ri', 'al', 'sp', 'oi', 'nt' 

Let’s assume another scenario, where the spaces in between the characters in the input string and those spaces will also be counted in some scenarios.

Input = 'Hello my movie is RRR' 
Output = 'He', 'll', 'o ', 'my', ' m', 'ov', 'ie', ' i', 's ', 'RR', 'R' 

We have ample number of ways to split the large strings into n size chunks in JavaScript. Let’s look into the following examples below.

Split() method

The split() method in JavaScript will split the string into an array of (sub)strings. This method will return the output in a new array and will not modify the original string.

Splitting the words

In the following example below, we have an input string having some characters in it. And we have performed split(" ") method, which will return the string by splitting every individual word.

<html> <body> <button onClick = "split()"> Click </button> <h4 id = "output"></h4> <script> function split() { var string = "Hello my name is hrithik roshan"; const newArray = string.split(" "); document.getElementById("output").innerHTML = newArray; }; </script> </body> </html>

As we can see in the above output, the string got divided into individual words.

N chucked words

Now, following program divides the given input string into n sized chunks.

<html> <body> <script> var v = []; var str = "Hello my name is hrithik roshan" var t = str.split(""); for (var i = 0; i < t.length; i++) { if ((i % 3) == 2) { v.push(t[i - 2].concat(t[i - 1], t[i])); } } document.write(v); </script> </body> </html>

Example 2

Splitting the characters, including spaces

In the following example below, we have an input string with characters in it. By using split("") method, the string will be divided by each character. The spaces will also count as individual characters.

<html> <body> <button onClick = "split()">Click</button> <h4 id = "output"></h4> <script> function split() { var string = "Hello my name is Allu Arjun"; const newArray = string.split(""); document.getElementById("output").innerHTML = newArray; }; </script> </body> </html>

In the output, the string is divided into individual characters.

Example 3

Splitting with the limit parameter

In the following example below, we have input string and having some characters. We performed splitting by including limit parameter. As we gave 3 in limit parameter, this will return three individual words in the input string.

<html> <body> <button onClick = "split()"> Click</button> <h4 id = "output"></h4> <script> function split() { var string = "Winner is Neeraj chopra"; const newArray = string.split(" ", 3); document.getElementById("output").innerHTML = newArray; }; </script> </body> </html>

As we have passed 3 in the split() method, the string will be chunked into 3 individual words.

Regex() method

To perform splitting a string by regex, regex method has a parameter to include the size to chunk the given input string.

Syntax

If we want to get the extreme n-sized sub-string for any string, the following is the syntax −

str.match(/.{1,n}/g); // Enter size of substring in 'n'

If the string is having new lines or carraiage returns, then the following will be the syntax −

str.match(/(.|[\r
]){1,n}/g); // Enter size of substring in 'n'

Example

In the example below, we checked whether the input string is empty or not. If the input string is greater than 0, we have performed regex method and provided size of chunk the string. This method will also count the space in between characters.

<!DOCTYPE html> <html> <head> <button onClick = "regex()">Click me! </button> <p id = "para"> </p> <p id = "para1"> </p> <p id = "para2"> </p> <script> function regex(){ stringsplit = function(str, size) { while (str == null) return []; str = String(str); return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str]; } document.getElementById("para").innerHTML = stringsplit('You are in Hyderabad') + "<br>"; document.getElementById("para1").innerHTML = stringsplit('Jaipur is a pink city',3) + "<br>"; document.getElementById("para2").innerHTML = stringsplit('Vizag is city of destiny',4); }; </script> </head> </html>

Updated on: 23-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements