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: ""
9 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.
I conceive this site has got some real excellent information for everyone. “The foundation of every state is the education of its youth.” by Diogenes.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Your writing style is cool and I have learned several just right stuff here. I can see how much effort you’ve poured in to come up with such informative posts. If you need more input about Cosmetics, feel free to check out my website at FQ7
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Marcelino XQAwafGSBtzBSDsh 6 19 2022 priligy 30 mg B Body weights of mice under the conditions in A
Good content
Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.