![]() ![]() Next case is the same result, only this time, we used a negative value for the start position. We did not specify the end position, so we took all the rest till the end. Second case starts at index 6 which means the first character in the sliced substring is 7th character. So not very useful since we want to slice only part of the string, right? Let’s fix it then. If we do not specify anything, the whole string is used. This information will be important with the negative positions later.įirst case is basic usage. We first get the length of the string we will be working with. const str = "Hello Dev Newbs!" // length of the string "Length: " + str.length // Length: 16 // getting the whole string str.slice() // Hello Dev Newbs! // start slice at position 6 (7th character) str.slice(6) // Dev Newbs! // using negative start position // length + negative value = position // 16 - 10 = 6 -> start slice at // position 6 (7th character) str.slice(-10) // Dev Newbs! // start slice at position 10 (11th character) // & end at position 14 (15th character) str.slice(10, 15) // Newbs // using negative positions // 16 - 6 = 10 -> start slice at // position 10 (11th character) // 16 - 1 = 15 -> end slice at // position 15 (16th character) str.slice(-6, -1) // Newbs Let’s see what all the fuss is about in the first example. When you specify a negative number either for the start position or the end position, the count goes from the end towards the start. Pro tip for you is that you can actually use a negative number to select from the end of the string. If we omit this parameter, the sliced substring goes from start position to the end of the string. The second parameter is optional and specifies the position up to, but not including where the extraction ends. The first parameter is the mandatory and specifies start position for the extraction to take place. The slice() method extracts parts of a string and returns the extracted parts in a new string. ![]() Haha! Like anybody could confuse them, right? ![]() ![]() The method of the day is slice(), not to be mistaken for the other slice() method. Hello and welcome back to the next episode my fellow devs! We are going to slice and dice today. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |