CRT-600 practice question 12 of 30

Refer to the string below: const str = 'Salesforce'; Which two statements result in the word 'Sales'? Choose 2 answers

Full set: 223 questions
Answer options
A: str.substr(1, 5);
B: str.substr (0, 5); Correct answer
C: str.substring (1, 5);
D: str.substring (0, 5); Correct answer
Correct Answer:
B. str.substr (0, 5);; D. str.substring (0, 5);
Explanation

The goal is to extract the substring 'Sales' from 'Salesforce'. The substring(startIndex, endIndex) method extracts characters from startIndex up to, but not including, endIndex. str.substring(0, 5) starts at index 0 and extracts characters up to index 5, resulting in 'Sales'. The substr(startIndex, length) method extracts a substring of a specified length starting from startIndex. str.substr(0, 5) starts at index 0 and extracts 5 characters, also resulting in 'Sales'. Both statements correctly produce the desired output.

Why Incorrect

A. str.substr(1, 5);: This extracts 5 characters starting from index 1, which results in 'alesf'.
C. str.substring(1, 5);: This extracts characters from index 1 up to (but not including) index 5, resulting in 'ales'.

References

1. Mozilla Developer Network (MDN) Web Docs, String.prototype.substring(): "The substring() method returns the part of the string from the start index up to and excluding the end index...". See the "Syntax" and "Examples" sections.

2. Mozilla Developer Network (MDN) Web Docs, String.prototype.substr(): "The substr() method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards." See the "Syntax" and "Examples" sections. Note: This source also marks substr() as a legacy feature.

3. MIT OpenCourseWare, 6.170 Software Studio, Spring 2013, Lecture 2: JavaScript: The lecture notes cover JavaScript fundamentals, including string manipulation. The behavior of substring(i, j) (characters from i to j-1) and substr(i, len) (len characters starting at i) is described, aligning with the correct answer. (See section on "Strings").

Scroll to Top