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 thestartandendparameters, which count from the end of the string.String.substring(start, end)does not accept negative values forstartandend.
Out-of-Range Values:
- If the 
startvalue is greater than theendvalue,String.slice()will return an empty string. - If the 
startvalue is greater than theendvalue inString.substring(), it will swap the values and return the substring. 
- If the 
 Default Behavior:
- When both 
startandendparameters are omitted,String.slice()returns the entire string. - When both 
startandendparameters 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