Ad

Quick implementation of splitter algorithm with use of regular expressions.

Probably could be done better if offset characters would be cut off & added to result array rather than adding some random chars to _str and removing them right before returning result.

Also instead of using regexp straightforward for-loop can make it better - because of lack of positive lookbehind in js rexegp implementations results are not always OK (problem with strings which length is not divisible by _n).

Code
Diff
  • function splitter (_str, _n) {
      _n = parseInt(_n);
      
      var offset = _n - _str.length % _n;
      
      if (offset !== _n) {
        _str += Math.pow(10, offset - 1);
      }
      
      var result = _str.split(new RegExp('(?=(?:.{' + _n + '})+$)', 'g'));
      
      if (offset !== _n) {
        var len = result.length,
            lastGroup = result[len - 1];
        
        result[len - 1] = lastGroup.substring(0, lastGroup.length - offset);
      }
      
      return result;
    }
    • console.log(
    • '123456'.split('')
    • );
    • function splitter (_str, _n) {
    • _n = parseInt(_n);
    • var offset = _n - _str.length % _n;
    • if (offset !== _n) {
    • _str += Math.pow(10, offset - 1);
    • }
    • var result = _str.split(new RegExp('(?=(?:.{' + _n + '})+$)', 'g'));
    • if (offset !== _n) {
    • var len = result.length,
    • lastGroup = result[len - 1];
    • result[len - 1] = lastGroup.substring(0, lastGroup.length - offset);
    • }
    • return result;
    • }