JS Coding Questions Logo
JS Coding Questions
#470💼 Interview💻 Code

What is the difference between substring and substr methods?

Advertisement

728x90

Both substring and substr are used to extract parts of a string, but there are subtle differences between the substring() and substr() methods in terms of syntax and behavior.

1. substring(start, end)

- Parameters:

- start: The index to start extracting (inclusive).

- end: The index to stop extracting (exclusive).

- Behavior:

- If start > end, it swaps the arguments.

- Negative values are treated as 0.

javascript
1let str = "Hello World";
2  console.log(str.substring(0, 5));   // "Hello"
3  console.log(str.substring(5, 0));   // "Hello" (swapped)
4  console.log(str.substring(-3, 4));  // "Hell" (negative = 0)

2. substr(start, length) _(Deprecated)_

- Parameters:

- start: The index to start extracting.

- length: The number of characters to extract.

- Behavior:

- If start is negative, it counts from the end of the string.

- If length is omitted, it extracts to the end of the string.

javascript
1let str = "Hello World"; console.log(str.substr(0, 5)); // "Hello" 
2  console.log(str.substr(-5, 3)); // "Wor" (starts from 'W')`

Note: substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 42

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
470of476
What is the difference between substring and substr methods? | JSCodingQuestions.com