Javascript - Parts of strings
Code Life
By Pierre Marsaa
Extracting Parts with .slice()
Let's see more string methods! I hope you remember indexing.
Sometimes you need to extract just a portion of a string. The .slice() method lets you grab a specific part of a string by specifying where to start and where to end.
The syntax is: string.slice(startIndex, endIndex)
Important: The end index is exclusive (not included in the result)!
↗️
Loading editor...
↶
↷
If you don't provide an end index, .slice() will extract all the way to the end of the string.
↗️
Loading editor...
↶
↷
You can also use negative indices to count from the end of the string:
↗️
Loading editor...
↶
↷
Remember: Strings are Immutable
The .slice() method doesn't modify the original string. It creates and returns a new string with the extracted portion. The original string remains unchanged.
Verify