javascript string slice

hljs.highlightAll();

JavaScript String Slice

JavaScript string slice method extracts a part of a string and returns the extracted part in a new string.

Syntax


string.slice(startIndex[, endIndex]);

The slice method takes two arguments:

  • startIndex - Required. The position where to begin the extraction. The first character has an index of 0.
  • endIndex - Optional. The position where to end the extraction (not included). If omitted, slice() extracts to the end of the string.

Example 1


const str = "Hello World!";
const result = str.slice(6);
console.log(result); // Output: World!

In this example, we have used the slice method to extract the substring starting from index 6 of the "Hello World!" string.

Example 2


const str = "Hello World!";
const result = str.slice(0, 5);
console.log(result); // Output: Hello

In this example, we have used the slice method to extract the substring starting from index 0 and ending at index 5 of the "Hello World!" string.

Multiple Ways to Use Slice Method

There are multiple ways to use the slice method:

  • Slice can take negative index as an argument. In that case, it starts extracting from the end of the string.
  • Slice can also be used with the length property of a string to extract a substring from the end of the string.

Example 3


const str = "Hello World!";
const result = str.slice(-6);
console.log(result); // Output: World!

In this example, we have used the slice method with a negative index to extract the substring starting from the 6th character from the end of the string.

Example 4


const str = "Hello World!";
const result = str.slice(-6, -1);
console.log(result); // Output: Worl

In this example, we have used the slice method with a negative index to extract the substring starting from the 6th character from the end of the string and ending at the 1st character from the end of the string.

Example 5


const str = "Hello World!";
const result = str.slice(-5);
console.log(result); // Output: rld!

In this example, we have used the slice method with the length property of the string to extract the substring starting from the 5th character from the end of the string.

I remember when I first started learning JavaScript, I was quite confused about the string slice method. However, after using it in a few projects, I realized how powerful it can be. The slice method allows me to extract a part of a string and use it elsewhere in my code. I have used it to extract substrings from URLs, to extract file extensions from file names, and to extract usernames from email addresses. The multiple ways of using the slice method make it even more versatile. I highly recommend any beginner to learn this method in order to be able to manipulate strings effectively in their JavaScript projects.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe