Created
April 25, 2017 02:43
-
-
Save mcaskill/ace8dfff879a5aba922756dd98769269 to your computer and use it in GitHub Desktop.
JS : Split a string by string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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