What is the difference between slice(), substring(), and substr() functions in JavaScript?
Question
What is the difference between slice(), substring(), and substr() functions in JavaScript?
Solution
The slice(), substring(), and substr() are all string methods in JavaScript that return a new string from a specified index. However, they have some differences in their functionality:
-
slice() method:
- It extracts a section of a string and returns it as a new string.
- It takes 2 parameters: the beginning index (inclusive) and the end index (exclusive). If the end index is not specified, it extracts till the end of the string.
- It can accept negative indexes, where -1 is the last index, -2 is the second last, and so on.
-
substring() method:
- It is similar to slice(). However, it cannot accept negative indexes.
- If the second parameter is smaller than the first one, this method will swap the parameters. For example, str.substring(1, 0) is the same as str.substring(0, 1).
-
substr() method:
- It is different from the above methods. The first parameter is the starting index and the second parameter is the length of the extracted part.
- If the first parameter is negative, it counts from the end of the string.
- Note: This method is considered a legacy function and should be avoided when possible. It's not a part of the core JavaScript language and may not be implemented in all browsers.
Similar Questions
How does the trim() function modify a JavaScript string?
What are string slices? Can you provide an example of its usage?
Which of the following methods in StringBuffer returns a substring based on the specified indices?a)substring()b)substr()c)subString()d)slice()
Which of these statements is true about slicing strings?1 pointThe slice() method can be used to slice a string.If the starting index is negative, Python generates a runtime error.If the starting index is negative, Python counts backward from the end of the string.When slicing a string, you must always provide both the starting and ending indexes.
Which method is used to merge two strings in JavaScript?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.