Table of Contents
- Code and its Explanation
Here str is the original string
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.
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"
- 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)