1var str1 = "Apple, Banana, Kiwi";
2
3var res1 = str1.slice(7, 13);
4var res2 = str1.slice(-12, -6);
5var res3 = str1.slice(7);
6var res4 = str1.slice(-12);
7var res5 = str1.substring(7, 13); //substring() cannot accept negative indexes like slice.
8var res6 = str1.substr(7, 9); // substr(start, length) is similar to slice(). second parameter of substr is length of string
9
10document.write("<br>" + "slice:", res1);
11document.write("<br>" + "slice -ve pos:", res2);
12document.write("<br>" + "slice with only start pos:", res3);
13document.write("<br>" + "slice with only -ve start pos", res4);
14document.write("<br>" + "substring:", res5);
15document.write("<br>" + "substr:", res6);
1/"slice() copies or extracts a given number of elements to a new array"/
2
3let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
4
5let todaysWeather = weatherConditions.slice(1, 3);
6// todaysWeather equals ['snow', 'sleet'];
7// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
1/*Use string concatenation and two slice() methods to print
2'JS' from 'JavaScript'.*/
3
4let language = 'JavaScript';
5console.log(language.slice(0,1)+language.slice(4,5));
6
7//JS
1JavaScript Array slice() Method The slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Note: The original array will not be changed.
1const string="Hi my name is mezen";
2string.slice (2); // return string without the character of index 2;
3string.slice (6); // return string without the character of index 6;
4
5string.slice (3,7) /* return 'my na' (m of index 3; a of index 7) including the
6 blank spaces */
1//The slice() method extracts a section of a string and returns
2//it as a new string, without modifying the original string.