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: ""
2 Comments
I pay a quick visit every day a few web sites and blogs
too read content, except this website offers quality based
articles. https://Www.waste-ndc.pro/community/profile/tressa79906983/
I like the comprehensive information you provide in your blog. The topic is kinda complex but I’d have to say you nailed it! Look into my page 57N for content about Airport Transfer.