Skip to content

Instantly share code, notes, and snippets.

@matthewnolan
Last active December 20, 2015 05:49
Show Gist options
  • Save matthewnolan/6081520 to your computer and use it in GitHub Desktop.
Save matthewnolan/6081520 to your computer and use it in GitHub Desktop.
JavaScript format page numbers like a printer dialog. "1,3,4-7" returns an array [1,3,4,5,6,7]
function findPages (pages) {
// usecase = "1-3,6,9";
if (typeof(pages) != "string"){ return }; // must be a string
var splitUse = pages.split(",") // ["1-3","6","9"]
var patt1 = new RegExp("-"); // search for -
for (i=0;i < splitUse.length;i++) {
if ( patt1.test(splitUse[i]) ){ // tests for "-"
var newsub = splitUse[i].split("-");
for (n=newsub[0]; n<=newsub[1]; n++){
splitUse.push(n); // adds contents to end of array
}
splitUse.splice(i,1);
}
splitUse[i] = parseInt(splitUse[i]); //convert string to number
if ( isNaN(splitUse[i]) ) { //cleans out any junk NaN from bad entry
splitUse.splice(i,1);
i--;
};
}
return splitUse.sort(function(a,b){return a-b}); // [1,2,3,6,9]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment