Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
JavaScript provides several ways to extract parts of a string.
slice()
Returns a new string from the part between the begin and end positions. The original string is not mutated.
'This is my car'.slice(5) //is my car
'This is my car'.slice(5, 10) //is my
The end parameter is optional. If omitted, extraction continues to the end of the string.
Negative parameters count from the end of the string:
'This is my car'.slice(-6) //my car
'This is my car'.slice(-6, -4) //my
substring()
Similar to slice(), but with different handling of edge cases:
- If any parameter is negative, it’s converted to 0
- If any parameter is higher than the string length, it’s converted to the string length
'This is my car'.substring(5) //'is my car'
'This is my car'.substring(5, 10) //'is my'
'This is my car'.substring(5, 200) //'is my car'
'This is my car'.substring(-6) //'This is my car'
'This is my car'.substring(-6, 2) //'Th'
'This is my car'.substring(-6, 200) //'This is my car'
slice() vs substring()
The main differences:
slice()accepts negative indexes (counting from end),substring()treats them as 0slice()returns empty string if start > end,substring()swaps the arguments
Use slice() when you need negative indexing. Use substring() when you want the arguments to be automatically adjusted.
split()
Splits a string into an array of substrings based on a separator:
const phrase = 'I love my dog! Dogs are great'
const tokens = phrase.split('dog')
tokens //["I love my ", "! Dogs are great"]
Split is case sensitive.
Common uses:
// Split by space to get words
'Hello World'.split(' ') //['Hello', 'World']
// Split by empty string to get characters
'Hello'.split('') //['H', 'e', 'l', 'l', 'o']
// Split by newline
'Line1\nLine2'.split('\n') //['Line1', 'Line2']
Getting String Until a Character
Use split() to get everything before a specific character:
const str = 'test-hey-ho'
str.split('-')[0] //'test'
Cutting a String into Words
const text = "Hello World! Hey, hello!"
text.split(" ")
// [ 'Hello', 'World!', 'Hey,', 'hello!' ]