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
1let input = "[email protected]";
2let atIndex = input.indexOf("@");
3let username = input.slice(0, atIndex);
4console.log(username);
Output
fake.email