Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Created April 25, 2017 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/ace8dfff879a5aba922756dd98769269 to your computer and use it in GitHub Desktop.
Save mcaskill/ace8dfff879a5aba922756dd98769269 to your computer and use it in GitHub Desktop.
JS : Split a string by string
if (!String.prototype.explode) {
/**
* Split a string by string
*
* Splits a String object into an array of substrings, each of which is formed
* by splitting it on boundaries formed by the string delimiter.
*
* @link http://locutus.io/php/explode/ Created by Kevin van Zonneveld (http://kvz.io)
* @example
* 'Kevin van Zonneveld'.explode(' ') // [ 'Kevin', 'van', 'Zonneveld' ]
* 'Kevin van Zonneveld'.explode(' ', 2) // [ 'Kevin', 'van Zonneveld' ]
* 'Kevin van Zonneveld'.explode(' ', -2) // [ 'Kevin' ]
*
* @param {String} [separator] - Optional. The boundary string. The separator is treated
* as a string or a regular expression.
*
* If separator is omitted or does not occur in the String, the array returned contains
* one element consisting of the entire string. If separator is an empty string,
* the String is converted to an array of characters.
*
* @param {Integer} [limit] - Optional. If `limit` is set and positive, the returned array will contain
* a maximum of `limit` elements with the last element containing the rest of string.
*
* If the `limit` parameter is negative, all components except the last -`limit` are returned.
*
* If the `limit` parameter is zero, then this is treated as 1.
* @return {String[]} An array of strings created by splitting the string parameter on boundaries
* formed by the `separator`.
*/
String.prototype.explode = function (separator, limit)
{
var str = this.split(separator);
if (typeof limit === 'undefined') {
return str;
}
// Support for limit
if (typeof limit !== 'number' || limit === 0) {
limit = 1;
}
// Positive limit
if (limit > 0) {
if (limit >= str.length) {
return str;
}
return str.slice(0, limit - 1).concat([ str.slice(limit - 1).join(separator) ]);
}
// Negative limit
if (-limit >= str.length) {
return [];
}
str.splice(str.length + limit);
return str;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment