String Slicing in JS

String slicing means creating a substring from part of another string.

The common pattern is:

string.slice(start, end)

The start index is included. The end index is not included.

Basic Example

const fullName = "Bro Code"
 
const firstName = fullName.slice(0, 3)
const lastName = fullName.slice(4, 8)
const firstChar = fullName.slice(0, 1)
const lastChar = fullName.slice(-1)
 
console.log(firstName)
console.log(lastName)
console.log(firstChar)
console.log(lastChar)

Split Full Name

const fullName = "Broseph Code"
 
const firstName = fullName.slice(0, fullName.indexOf(" "))
const lastName = fullName.slice(fullName.indexOf(" ") + 1)
 
console.log(firstName)
console.log(lastName)