What is Difference between substr() and substring() in JavaScript?

The difference between substr() and substring() in JavaScript is that substr() is used to extract a specified number of characters from a given string, starting from a specified position, while substring() is used to extract the characters from a string between two specified indices. substr() can accept negative index values, while substring() cannot.

See below example

var str = "Hello world!";
var res = str.substr(1, 4);

console.log(res); // ello

var str = "Hello world!";
var res = str.substring(1, 4);

console.log(res); // ell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: