- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript String slice
JavaScript Strings
JavaScript String slice
slicetakes a piece out of a string without changing the original.
It works just like slice on an array.
The end index is not included, which catches people out.
Example
Example
javascript
const text = "JavaScript";
console.log(text.slice(0, 4));
console.log(text.slice(4));The output is Java then Script.
Taking Pieces
slice(start, end) returns the characters from start up to but not including end.
Leaving out the end takes everything to the finish.
Negative numbers count from the end.
Syntax
Syntax
javascript
text.slice(start, end);The original string is never changed.
Negative Indexes
This is the easiest way to take the last few characters.
Example
Example
javascript
const file = "report.pdf";
console.log(file.slice(-3));
console.log(file.slice(0, -4));The output is pdf then report.
slice and substring
substring is similar but treats negatives as 0.
slice is usually the one you want.
Example
Example
javascript
const text = "JavaScript";
console.log(text.slice(-6));
console.log(text.substring(-6));substring ignored the negative and returned everything.
A Single Character
charAt, brackets and at all work.
Example
Example
javascript
const text = "hello";
console.log(text.charAt(1));
console.log(text[1]);
console.log(text.at(-1));at is the only one that accepts a negative index.
Splitting a Name
Combining indexOf with slice is a common pattern.
Example
Example
javascript
const full = "Ada Lovelace";
const space = full.indexOf(" ");
console.log(full.slice(0, space));
console.log(full.slice(space + 1));split does this more directly, as the next lessons show.
Shortening Text
Adding an ellipsis when the text is too long.
Example
Example
javascript
function shorten(text, max) {
return text.length <= max ? text : text.slice(0, max) + "...";
}
console.log(shorten("A very long title", 6));
console.log(shorten("Short", 6));Only the first was long enough to be cut.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript String slice</title>
</head>
<body>
<h1>String slice</h1>
<p id="out"></p>
<script>
const text = "JavaScript Basics";
document.getElementById("out").innerHTML =
"First word: " + text.slice(0, text.indexOf(" ")) +
"<br>Last six: " + text.slice(-6) +
"<br>Shortened: " + text.slice(0, 10) + "...";
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try different numbers:
Change the slice positions and watch the pieces change.
Important Points
slice(start, end)excludes the end index.- Leaving out the end takes the rest of the string.
- Negative indexes count from the end.
substringtreats negatives as 0.- The original string is never changed.
Conclusion
slice is the everyday tool for taking part of a string.
Negative indexes make working from the end easy.
Prefer it to substring, which behaves less predictably.
