Master JavaScript String slice() Method

December 21, 2023
Master JavaScript String slice() Method
Table of Contents
  • slice() with positive indexes
  • slice() with negative indexes
  • Omitting the second argument
  • Browser Compatibility

In JavaScript, the slice() method is a powerful tool for manipulating strings. It can extract parts of a string and return the extracted parts in a new string.

1let str = "Hello, World!";
2let res = str.slice(7, 13); // returns "World!"

The slice() method accepts two arguments: the start position, and the end position (optional). If the end position is omitted, the method slices out the rest of the string.

slice() with positive indexes

Positive indexes represent positions at the start of the string. The first character is at position 0.

1let str = "Hello, World!";
2let res = str.slice(0, 5); // returns "Hello"

slice() with negative indexes

Negative indexes represent positions at the end of the string. The last character is at position -1.

1let str = "Hello, World!";
2let res = str.slice(-6, -1); // returns "World"

Omitting the second argument

If you omit the second argument, slice() will return the rest of the string.

1let str = "Hello, World!";
2let res = str.slice(7); // returns "World!"

Browser Compatibility

All modern browsers fully support the slice() method. For a deeper dive into JavaScript strings, check out our Learn JavaScript course. If you're new to web development, we recommend starting with our HTML Fundamentals course and Introduction to Web Development course before moving on to JavaScript. Once you're comfortable with JavaScript, you can take your skills to the next level with our CSS Introduction course.

Here are some additional resources that you may find helpful: Mozilla Developer Network's guide on JavaScript's slice() method, W3School's tutorial on JavaScript String slice() Method, and's chapter on strings.

Related courses

1 Course

Javascript Fundamentals Course

Javascript Fundamentals

834 reviews

Stay Ahead with Code highlights

Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.

3D Letter

Related articles

119 Articles

Start learning for free

If you've made it this far, you must be at least a little curious. Sign up and grow your programming skills with Code Highlights.

Start learning for free like this happy man with Code Highlights