Does anyone know what the difference is between these two methods?
String.prototype.slice
String.prototype.substring
Does anyone know what the difference is between these two methods?
String.prototype.slice
String.prototype.substring
I’ve worked with JavaScript for quite a while now, and one of the early confusions I faced was the subtle difference between slice
and substring
. Here’s the gist of it when it comes to javascript substring vs slice
:
In JavaScript, the slice method extracts characters from a string starting from the given start index up to, but not including, the end index. It also accepts negative values, which means it can count from the end of the string. On the other hand, the substring method also returns a portion of the string, but it does not support negative values. If the start index is greater than the end index, substring will automatically swap the two values before extracting.
let str = "Hello, world!";
console.log(str.slice(0, 5)); // "Hello"
console.log(str.substring(0, 5)); // "Hello"
So both seem similar until you start playing with edge cases.
Ah yes, @miro.vasil’s got it right. I’ve run into some quirky bugs while dealing with javascript substring vs slice
, especially when dealing with negative indices or reversed ranges. Here’s what I’ve learned:*
slice
accepts negative values, so slice(-6)
gives you the last 6 characters.substring
, negative values get treated as 0
, and it will swap start
and end
if needed.slice
will return an empty string if start > end
, whereas substring
makes it work by flipping the values.let str = "Hello, world!";
console.log(str.slice(-6)); // "world!"
console.log(str.substring(-6)); // "Hello, world!" (negative converted to 0)
Subtle behaviors, but important if you want predictable results.”
Totally agree with @miro.vasil and @jacqueline-bosco. I’ve seen junior devs get tripped up when they assume slice
and substring
are interchangeable. Here’s how I usually break down javascript substring vs slice
when mentoring:*
slice
, negative indices are super useful when trimming from the end. But be cautious—slice(4, 1)
gives you an empty string since it doesn’t auto-correct.substring
, on the other hand, is more forgiving—it flips the values if needed but ignores any negative numbers.let str = "Hello, world!";
console.log(str.slice(1, 4)); // "ell"
console.log(str.substring(1, 4)); // "ell"
console.log(str.slice(4, 1)); // ""
console.log(str.substring(4, 1)); // "ell"
So while both are great for string slicing, understanding these nuances really helps you write bug-free code.”