In JavaScript, we have a “string” dataType and it gives us some inbuilt functions now it gives us two functions one is the substring() and the second is the slice().
now the substring method is used to get part of a string. Think of it as a way to cut out a piece of the string. You tell the substring() method where to start and where to stop cutting the string.
for example:
let str = "hello world!" console.log(str.substring(0,2)) //output: "he"
now the slice method also works in the same way it takes the starting index and end index and returns the character between the given indexes
for example:
let str = "hello world!" console.log(str.slice(0,2)) //output: "he"
the output of the slice and substring method is the same so what is the main difference between them?
the main difference between the substring and slice methods is :
- Handling Negative Indices:
substring(): If you use negative values, they are treated as 0.
slice(): Negative values count from the end of the string.
let str = "Hello, World!"; console.log(str.substring(0,-1)) // Output: "" console.log(str.substring(-1,3)) // Output: "Hel" console.log(str.substring(1,-3)) // Output: "H" console.log(str.substring(0,-1)) // Output: "Hello, World"
2. Order of Parameters:
substring(): If the start index is greater than the end index, the substring will swap the values.
slice(): If the start index exceeds the end index, the slice will return an empty string.
let str = "Hello, World!"; console.log(str.substring(4,2)) // Output: "ll" console.log(str.slice(4,2)) // Output: ""
3 Comments
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your article helped me a lot, is there any more related content? Thanks!