Slicing a string using Javascript slice


Introduction

In this article, we look at the Javascript Slice method then we’ll dive into the code and lastly, we shall look at its limitations.

Table of Contents

  • What is Javascript Slice?
  • Parameters of Javascript Slice
  • Code and its Explanation
  • Limitation & Caveats of Using Javascript Slice
  • Other Related Concepts

What is Javascript Slice?

The Slice method in javascript is used to extract a particular section of a string without modifying the original string. Also, the extracted section is returned as a new string.

Syntax of Javascript Slice function

str.slice(beginIndex[, endIndex])

Here str is the original string

Parameters required for Javascript Slice

beginIndex

The beginIndex parameter in Javascript Slice is used to indicate the index at which the extraction should begin. Negative Indexes can also be used to indicate the index.

Example: In order to extract “ple” from “Flexiple” the beginIndex should be 5 as the index of “p” is 5.

Note:An empty string would be returned, In case the beginIndex is greater than or equal to the length of the string.


endIndex

Subsequently, the endindex parameter in Javascript Slice is used to indicate the index at which the extraction would end. And similar to beginindex, negative indexes can also be used, this would come in handy especially when you are dealing with longer strings.

Example: In order to extract “ple” from “Flexiple” the beginIndex should be 5 and the endindex should be 7 as the index of “e” is 7.

Note: The endinIndex parameter is optional, i.e, in case an endinIndex is specified it would end there else the slice function would end at the last index of the given string.

Code and its Explanation

const str = 'Hire the top 1% freelance developers and designers.';

console.log(str.slice(9, 24));
// expected output: "top 1% freelance"

console.log(str.slice(26));
// expected output: "developers and designers."

console.log(str.slice(-10));
// expected output: "designers."

console.log(str.slice(-42, -26));
// expected output: "top 1% freelance"

Limitation & Caveats of Using Javascript Slice

  • Ensure the endinindex is always greater than the begininIndex, else an empty string would be returned
  • Using negative index can be tricky, a tip is to make it easier is to consider it as (str.length + beginIndex/ endinIndex)