Computer >> Computer tutorials >  >> Programming >> Javascript

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


There are two ways to split a large string in to n-sized sub strings.

1) Conventional method

This is a pure logic method in which only conventional methods are used such as for loop, concat, modulous etc. This method is not as sophisticated as regex method, because it's a predetermined method. The number of chunks that string to be divided should be predetermined before starting coding.

In the following example the string "tutorixtutorixtutorix" is divided in to 3-chunks of sub strings.

Example

<html>
<body>
<script>
   var v = [];
   var str = "tutorixtutorixtutorix"
   var t = str.split("");
   document.write(t);
   document.write("</br>");
   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>

Output

tut,ori,xtu,tor,ixt,uto,rix


2) Regex method

It is not a predetermined method. Regex method provides a slot to mention the size to chunk the string. 

In general, for any string out of which you want to extract at-most n-sized sub strings, the syntax is

   str.match(/.{1,n}/g); // Replace n with the size of the substring

If the string contains any newlines or carriage returns, then the syntax is

  str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring

The original syntax of the code is

   function chunkString(str, size) {
     return str.match(new RegExp('.{1,' + size + '}', 'g'));
}

Example

<html>
<body>
<script>
   stringChop = function(str, size){
      if (str == null)
         return [];
         str = String(str);
         return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];
   }
   document.write(stringChop('tutorialspoint'));
   document.write("<br>");
   document.write(stringChop('tutorix',2));
   document.write("<br>");
   document.write(stringChop('tutorialspoint',3));
</script>
</body>
</html>

Output
["tutorialspoint"]
["tu","to","ri","x"]
["tut","ori","als","poi","nt"]