What is the Difference Between Substr and Substring

There are two String manipulation functions in JavaScript, namely, substr() and substring(), that are used to get a substring from a String. However, there are slight differences between subst() and substring() methods.

Both functions take two parameters, but substr() takes the length of the substring to be returned, while substring takes end index (excluding) for a substring.

substr()

p>The substr() 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 substr() method:

Javascript substr method
let str = "Welcome to W3Docs"; console.log(str.substr(1,2)); console.log(str.substr(-2,2)); console.log(str.substr(1)); console.log(str.substr(-17,2));

substring()

The substring() 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 the example of substring():

Javascript substring method
let str = "Welcome to W3Docs"; console.log(str.substring(1,2)); console.log(str.substring(0, 10)); console.log(str.substring(5));

Though substr() is not strictly a deprecated function, it is considered a legacy function and you should avoid using it as possible as you can. It is not part of JavaScript and may be removed in the future. So, you can use the substring() method instead.