Design & Download
Your JS Library
in Seconds!!!

Snippet: Splitting Strings

Written by Christopher West (cwest) on November 29, 2015.
Dices up a string splitting it on the passed in delimiter and placing the results in an array while making sure that the empty string is converted to an empty array.
function dice(str, delim, opt_limit) {
  var arr = [], start = 0, i;
  if (str) {
    str.replace(
      (typeOf(delim, 'RegExp') ? flagRegExp : quoteRegExp)(delim, 'g'),
      function(m) {
        i = arguments;
        i = i[i.length - 2];
        if (!(opt_limit-- < 1)) {
          arr.push(str.slice(start, i));
          start = i + (m.length || 1);
        }
      }
    );
    arr.push(str.slice(start));
  }
  return arr;
}

One of the funny things about String.prototype.split() is that if the string is the empty string, using split() on it will cause it to create an array where the 1st value is the empty string. In many cases, the desired result is that the resulting array simply be an empty array. YourJS.dice() was written for the specific purpose of making sure the empty string gets turned into the empty array after being "diced". The other difference is that when specifying a limit on how many times the string should be diced, this makes it so that the last substring in the returned array will contain the remaining part of the string.

dice() API Documentation

Description

Dices up a string splitting it on the passed in delimiter and placing the results in an array.

Parameters

  1. str {String}:
    The string to be diced and turned into an array of strings. If this is an empty string, an empty array will be returned.
  2. delim {RegExp|String}:
    The regular expression or string to be used as a delimiter in order to dice up str. The matched substrings will not be included in the strings returned in the array.
  3. opt_limit {Number}:
    Optional. Defaults to Infinity. If specified, this number represents the maximum number of times str will be split on delim. Unlike with String.prototype.split(), the remaining substring after this limit will simply be placed in the last element of the array.

Returns

Returns an array of substrings formed by dicing (splitting) up str by delim.