13/09/2023
let's see .slice(), .split() and .splice() methods. .slice() is used to make a substring from a string. for example:
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
and from this string if we want to cut out the portion starting from index 10 up to 50. we will do
console.log(paragraph.slice(10, 50));
it will give output as :
"brown fox jumps over the lazy dog. If th"
The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
let's see the code in action:
const str = 'the quick brown fox jumps';
console.log(str.split(""));
here we will get output as:
['t', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k', ' ', 'b', 'r', 'o', 'w', 'n', ' ', 'f', 'o', 'x', ' ', 'j', 'u', 'm', 'p', 's']
it means each character is now an element of the created array.
now if we do:
console.log(str.split(" "));
note that we have intentionally put a space between the inverted commas. this time the console will return:
['the', 'quick', 'brown', 'fox', 'jumps']
have you noticed the difference?
splice() method is used for changing the element at some specified index in an array. let's clear it with example. Suppose we have an array:
const fruits = ['apple', 'orange', 'banana', 'kiwi'];
now we want to replace the "orange" with mango. the index of orange is 1.
const summerFruits = fruits.splice(1, 1, "mango");
Here the first argument 1 means the index at which we want our replacement to be incorporated and the second 1 means the number of items that will be popped out of the array. and finally the 'mango' is the word that we want to be put at index 1 in this array.
console.log(summerFruits);
console will return ['orange'] as it has been omitted from the array.
now we want to check the changes in array :
console.log(fruits);
it will return :
['apple', 'mango', 'banana', 'kiwi']
orange has been replace with mango now.
Explore more in these method to mastery your skills.