Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
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'; console.log(y); // tutorialspoint
tutorialspoint
Splitting a Large String into Chunks
We need to split a String 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 ?
Input = 'Tutorialspoint' Output = 'Tu', 'to', 'ri', 'al', 'sp', 'oi', 'nt'
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.
Using a For Loop Approach
The simplest way to split a string into chunks is using a for loop with substring method.
<html>
<body>
<button onClick="splitString()">Click to Split String</button>
<h4 id="output"></h4>
<script>
function splitString() {
var string = "Hello my name is hrithik roshan";
var chunkSize = 3;
var chunks = [];
for (var i = 0; i < string.length; i += chunkSize) {
chunks.push(string.substring(i, i + chunkSize));
}
document.getElementById("output").innerHTML = chunks.join(', ');
}
</script>
</body>
</html>
Hel, lo , my , nam, e i, s h, rit, hik, ro, sha, n
Using Regular Expression (Regex) Method
To perform splitting a string by regex, we can use the match() method with a regular expression pattern to specify the chunk size.
Syntax
If we want to get the n-sized sub-strings 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 carriage returns, then the following will be the syntax ?
str.match(/(.|[\r<br>]){1,n}/g); // Enter size of substring in 'n'
Example
<html>
<head>
<button onClick="regexSplit()">Click me!</button>
<p id="para"></p>
<p id="para1"></p>
<p id="para2"></p>
<script>
function regexSplit() {
function stringSplit(str, size) {
if (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', 3);
document.getElementById("para1").innerHTML = stringSplit('Jaipur is a pink city', 3);
document.getElementById("para2").innerHTML = stringSplit('Vizag is city of destiny', 4);
}
</script>
</head>
</html>
You, ar,e i,n H,yde,rab,ad Jai,pur, is, a ,pin,k c,ity Viza,g is, cit,y of, des,tiny
Using Array.from() with Map
A modern approach using Array.from() to create chunks efficiently:
function chunkString(str, size) {
if (size <= 0) return [str];
const chunks = [];
for (let i = 0; i < str.length; i += size) {
chunks.push(str.slice(i, i + size));
}
return chunks;
}
const text = "JavaScript is awesome";
console.log(chunkString(text, 4));
console.log(chunkString(text, 3));
[ 'Java', 'Scri', 'pt i', 's aw', 'esom', 'e' ] [ 'Jav', 'aSc', 'rip', 't i', 's a', 'wes', 'ome' ]
Comparison
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| For Loop + substring() | Good | High | All browsers |
| Regex match() | Moderate | Moderate | All browsers |
| slice() with loop | Best | High | All modern browsers |
Conclusion
Splitting strings into chunks is useful for data processing and formatting. The for loop with slice() method provides the best balance of performance and readability for most use cases.
