split(),slice() and splice() in JavaScript

·

2 min read

split(),slice() and splice() in JavaScript

split(),slice() and splice() in JavaScript

JavaScript has various methods, which have similar functions and confusing sometimes(but actually not). In this blog let's see three important methods.

1. split()

split() method splits the string according to your need. and return the words into an array(split is a string method).

how?

Let's see step by step

Step-1

Declaring the string

const sentence = "I went to the office yesterday";

now I want each and every word of this sentence, omitting the white spaces.

Step-2

const extracedWords = sentence.split(" ");
console.log(extracedWords);

the space between the double quotes is the separator, which means the sentence is split by the spaces between them.

the result would be an ["I", "went", "to", "the" "office", "yesterday"]

2.slice()

slice() method returns part of the original array into a new array. slice() method has 2 parameters i.e starting point and ending point(sometimes the ending point may be optional). The original array remains unchanged.

still confused? Let's see an example.

const arr1 = ["One", "Two","Three", "Four", "Five","Six"];
const newArr = arr1.slice(1, 3);

here in arr1.slice(1,3) 1 is the starting point and 3 is the ending point, to be precise I want the elements between indexes 0 and 3. Therefore start from index 1 and ends before index 3.

console.log(newArr); // [ "Two","Three"]
console.log(arr1);  //["One", "Two","Three", "Four", "Five","Six"];

3.splice()

slice() and splice() would be confusing at first, it's simple to understand. The splice() method modifies the elements in an array by adding, removing, or replacing the elements in the original array. This usually comes with 3 parameters. i.e Array.prototype.splice(starting index, removing index, item to be added);

const arr = ["One", "Three", "Four", "Five"];
const filteredArr = arr.splice(1, 0, "Two");
console.log(arr);

here in arr.splice(1,0,"Two")

  • 1 indicates the starting index where we want to make changes.

  • 0 indicating the number of old array elements to remove (since it is 0, no old element will be removed).

  • "Two" is the element to be added.

what would be the result then?

the result is ["One", "Two", "Three", "Four", "Five"]

Usage of splice() and slice()

1.If you want a part/portion of an array go for the slice() method. 2.If you want to modify an existing array go for the splice() method.

Thanks for reading ✌