Multiple choice general knowledge

How do substring() and substr() differ?

  1. One is not a method of the String object.

  2. substr() takes three arguments, substring() only two.

  3. Only one accepts a desired string length as an argument.

  4. Besides the spelling, nothing

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

substr() accepts a start position and length parameter, while substring() takes start and end positions. Only substr() allows specifying the desired string length directly. Option A is incorrect because both are String methods. Option B is wrong because neither takes three arguments. Option D is false because their parameter semantics differ fundamentally.

AI explanation

To understand the difference between the substring() and substr() methods in JavaScript, let's go through each option:

Option A) One is not a method of the String object. This option is incorrect because both substring() and substr() are methods of the String object in JavaScript.

Option B) substr() takes three arguments, substring() only two. This option is incorrect because both substr() and substring() can take two arguments. However, the arguments have different meanings.

Option C) Only one accepts a desired string length as an argument. This option is correct. The substr() method accepts a starting index and a length as arguments, where the length specifies the number of characters to extract. On the other hand, the substring() method accepts a starting index and an ending index as arguments, where the ending index is exclusive. It does not accept a desired string length as an argument.

Option D) Besides the spelling, nothing. This option is incorrect because there are differences between substring() and substr() in terms of the arguments they accept.

Therefore, the correct answer is C. Only one of the methods, substr(), accepts a desired string length as an argument.