What is the difference between String.slice and String.substring?

 

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():

  1. Negative Start Index:

    • String.slice(start, end) allows negative values for the start and end parameters, which count from the end of the string.
    • String.substring(start, end) does not accept negative values for start and end.
  2. Out-of-Range Values:

    • If the start value is greater than the end value, String.slice() will return an empty string.
    • If the start value is greater than the end value in String.substring(), it will swap the values and return the substring.
  3. Default Behavior:

    • When both start and end parameters are omitted, String.slice() returns the entire string.
    • When both start and end parameters are omitted, String.substring() also returns the entire string.

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