What is the Difference Between Substr and Substring
Read this JavaScript tutorial and learn about the two String manipulation functions, namely, substr() and substring() methods and difference between them.
There are two String methods in JavaScript, namely, <kbd class="highlighted">substr()</kbd> and <kbd class="highlighted">substring()</kbd>, that are used to extract a portion of a string. However, there are slight differences between <kbd class="highlighted">substr()</kbd> and <kbd class="highlighted">substring()</kbd> methods.
Both methods can take two parameters, but <kbd class="highlighted">substr()</kbd> uses a start index and a length, while <kbd class="highlighted">substring()</kbd> uses a start index and an end index (excluding).
substr()
<p>The <kbd class="highlighted">substr()</kbd> method is used to get a part of the string that starts at the specified index and extends for a specified number of characters afterwards. Here’s an example of the <kbd class="highlighted">substr()</kbd> method:
Javascript substr method
substring()
The <kbd class="highlighted">substring()</kbd> method is used to get the portion of the string that is between the start and end indexes, or to the end of the string. Here’s an example of the <kbd class="highlighted">substring()</kbd> method:
Javascript substring method
Note that substring() treats negative indices as 0, unlike substr() which counts from the end of the string.
Though <kbd class="highlighted">substr()</kbd> is not strictly a deprecated function, it is considered a legacy feature and you should avoid using it whenever possible. It is officially deprecated in the ECMAScript specification and may be removed in the future. So, you can use the <kbd class="highlighted">substring()</kbd> method instead.