-
Notifications
You must be signed in to change notification settings - Fork 2
JS String Prototype Slice
The JavaScript string method .slice()
extracts a portion of a string and returns a new string.
str.slice(beginSliceIndex[, endSliceIndex]);
beginSliceIndex
The zero-based index where the slice should begin. If beginSliceIndex is a negative number, .slice()
counts backwards from the end of the string to determine where to begin the slice.
endSliceIndex
Optional. The zero-based index where the slice should end. If omitted, .slice()
extracts to the end of the string.
.slice()
slices the text out of one string and returns a new string.
Using .slice()
to create a new string
var string1 = "Hello World!";
var string2 = string1.slice(3);
console.log(string2); // Will log "lo World!"
var string3 = string1.slice(3, 7);
console.log(string3); // Will log "lo W"
Using .slice()
with negative indices
var string = "Hello World!"
str.slice(-3); // Returns "ld!"
str.slice(-3, -1); // Returns "ld"
str.slice(0, -1); // Returns "Hello World"
Source MDN
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links