Skip to content

Instantly share code, notes, and snippets.

@z-------------
Created May 10, 2015 10:13
Show Gist options
  • Save z-------------/b68679eb2739bfd3e580 to your computer and use it in GitHub Desktop.
Save z-------------/b68679eb2739bfd3e580 to your computer and use it in GitHub Desktop.
Python-like string and array chopping
var chop = function(list, arr) {
var start = arr[0] || 0;
var end = arr[1] || list.length;
if (Array.isArray(list)) {
list = list.splice(start, end - start);
return list;
} else if (typeof list === "string") {
return list.substring(start, end);
}
return null;
};
/*
chop("spam", [1,]) => "pam"
chop("spam", [1,2]) => "p"
chop("spam", [,2]) => "sp
chop(["zero", "one", "two"], [,2]) => ["zero", "one"]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment