slice ExamplesΒΆ

The general syntax for this method is:

stringName.slice(i, j);

Given a starting index i and an optional ending index j, return the substring consisting of characters from index i through index j-1. If the ending index is ommitted, the returned substring includes all characters from the starting index through the end of the string.

"LaunchCode".slice(0, 6);

"LaunchCode".slice(6);

Output

Launch
Code

On some websites, the portion of an email address before the @ symbol is used as a username. We can extract this portion of an email address using slice in conjunction with indexOf.

Example

1
2
3
4
let input = "[email protected]";
let atIndex = input.indexOf("@");
let username = input.slice(0, atIndex);
console.log(username);

Output

fake.email