Knowee
Questions
Features
Study Tools

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?

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. 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.
  2. 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).
  3. 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.

This problem has been solved

Similar Questions

How can we extract "Pizza" from the string str = "Pizza Lover"?Astr.slice(0, 4)Bstr.slice(0, 5)Cstr.slice(4, 0)Dstr.slice(5, 0)

Which of the following methods in StringBuffer returns a substring based on the specified indices?a)substring()b)substr()c)subString()d)slice()

In which of the following ways can we create strings in JavaScript?A'A string'B"A string"C`A string`DAll of the above

Which of these is the correct syntax for string concatenation in JavaScript?A. str1 + str2None of these options.Both A and B.B. str1.concat(str2)

Problem statementSend feedbackWhat kind of scoping does JavaScript use?Options: Pick one correct answer from belowLiteralLexicalSegmentalSegmental

1/1

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.