Last updated: Mar 1, 2024
Reading timeยท2 min
To remove the first and last characters from a string, call the slice()
method, passing it 1
and -1
as parameters.
The String.slice()
method will return a copy of the original string with the
first and last characters removed.
const str = 'abcd'; const withoutFirstAndLast = str.slice(1, -1); console.log(withoutFirstAndLast); // ๐๏ธ bc
We passed the following arguments to the String.slice() method:
-1
means "go up to, but not including the last character
in the string".-1
and str.length - 1
is the same. We instruct the slice
method to go up to, but not including the last character in the string.The String.slice()
method doesn't mutate the original string, it returns a new
string. Strings are immutable in JavaScript.
Calling the slice()
method on an empty string doesn't throw an error, it
returns an empty string.
const str = ''; const withoutFirstAndLast = str.slice(1, -1); console.log(withoutFirstAndLast); // ๐๏ธ ""
Alternatively, you can use the String.substring()
method.
const str = 'abcd'; const withoutFirstAndLast = str.substring(1, str.length - 1); console.log(withoutFirstAndLast); // ๐๏ธ bc
We used the String.substring()
method to achieve the same result.
The String.substring() method returns a slice of the string from the start index to the excluding end index.
The method takes the following parameters:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
If no end
index is specified the slice goes to the end of the string.
There are a couple of
differences
between the String.substring()
and the String.slice()
methods:
substring()
method swaps its start and end index if the start index is
greater than the end index. The slice()
method returns an empty string in
this case.const str = 'bobby'; console.log(str.substring(3, 0)); // ๐๏ธ bob console.log(str.slice(3, 0)); // ๐๏ธ ''
substring()
are negative, they are
treated as if they were 0
.const str = 'bobby'; console.log(str.substring(-3)); // ๐๏ธ bobby console.log(str.slice(-3)); // ๐๏ธ bby
When given a negative index, the slice()
method counts backward from the end
of the string to find the indexes.
My personal preference is to use the String.slice()
method because it's more
intuitive than String.substring()
in many different scenarios.
You can learn more about the related topics by checking out the following tutorials: