JavaScript .slice()
Published May 4, 2022
Contribute to Docs
The .slice() method selects and returns a selected portion of a string.
Syntax
string.slice(start);
string.slice(start, stop);
- The
startindex is optional and begins at zero (inclusive) by default. - The
stopindex is also optional and defaults to the length of the string (not inclusive).
Example
In the example below, a smoothie string is created. Next, the .slice() method is used to extract substrings for the berry variable:
let smoothie = 'mango strawberry pineapple';let berry = smoothie.slice(6, 16);console.log(smoothie);console.log(berry);
The output will look like the following:
mango strawberry pineapplestrawberry
Codebyte Example
In the example below, an animals string is created. Next, the .slice() method is used to pick out substrings of certain animals, specifically birds:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours