Skip to content

Instantly share code, notes, and snippets.

@crimx
Last active August 29, 2015 14:03
Show Gist options
  • Save crimx/0d857ca82055162468cb to your computer and use it in GitHub Desktop.
Save crimx/0d857ca82055162468cb to your computer and use it in GitHub Desktop.
slice, substr, substring in JavaScript
String.prototype.slice(start[,end]); If a negative number is given, it is treated as strLength + start/end.
String.prototype.substr(start[,length]); If a negative number is given to start, it is treated as strLength + start.
String.prototype.substring(indexA[,indexB]); If either argument is less than 0 or is NaN, it is treated as if it were 0.
If either argument is greater than stringName.length, it is treated as if it were stringName.length.
var s1 = "0123456789"
console.log(s1.slice(3, 7)); //"3456"
console.log(s1.substr(3, 7)); //"3456789"
console.log(s1.substring(3, 7)); //"3456"
console.log(s1.slice(7, 3)); //""
console.log(s1.substr(7, 3)); //"789"
console.log(s1.substring(7, 3)); //"3456" (3, 7)
console.log(s1.slice(-3)); //"789" (10-3=7)
console.log(s1.substr(-3)); //"789" (10-3=7)
console.log(s1.substring(-3)); //"0123456789" (0)
console.log(s1.slice(-3, -7)); //"" (10-3=7, 10-7=3)
console.log(s1.substr(-3, -7)); //"" (10-3=7, 0)
console.log(s1.substring(-3, -7)); //"" (0, 0)
console.log(s1.slice(3, -7)); //"" (3, 10-7=3)
console.log(s1.substr(3, -7)); //"" (3, 0)
console.log(s1.substring(3, -7)); //"012" (3, 0 -> 0, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment