String.slice()
and String.substring()
are two methods in JavaScript used to extract a portion of a string. While they both serve a similar purpose, there are differences in how they work.
Here are the key differences between String.slice()
and String.substring()
:
Negative Start Index:
String.slice(start, end)
allows negative values for thestart
andend
parameters, which count from the end of the string.String.substring(start, end)
does not accept negative values forstart
andend
.
Out-of-Range Values:
- If the
start
value is greater than theend
value,String.slice()
will return an empty string. - If the
start
value is greater than theend
value inString.substring()
, it will swap the values and return the substring.
- If the
Default Behavior:
- When both
start
andend
parameters are omitted,String.slice()
returns the entire string. - When both
start
andend
parameters are omitted,String.substring()
also returns the entire string.
- When both
Here's an example demonstrating these differences:
javascript
const str = "Hello, World!";
// Using String.slice()
console.log(str.slice(0, 5)); // Output: "Hello"
console.log(str.slice(7)); // Output: "World!"
console.log(str.slice(-6)); // Output: "World!"
console.log(str.slice(6, 6)); // Output: ""
console.log(str.slice(12, 5)); // Output: ""
// Using String.substring()
console.log(str.substring(0, 5)); // Output: "Hello"
console.log(str.substring(7)); // Output: "World!"
console.log(str.substring(-6)); // Output: "Hello"
console.log(str.substring(6, 6)); // Output: ""
console.log(str.substring(12, 5)); // Output: "World!"
In this example, you can see that String.slice()
and String.substring()
behave differently when it comes to negative indices and out-of-range values. Understanding these differences can help you choose the appropriate method for your string manipulation needs.
Comments
Post a Comment