substr() vs substring() in JavaScript

substring() and substr() are among the most popular methods in JavaScript.

But, for a new developer, it creates confusion which one to use.

thought of clearing the minor difference that exists between these two APIs.

Let’s consider an example.

var text = “This world is a great place to live”;

 

// substring – Start trimming after the 5th character and cut text upto 10th character

console.log( text.substring ( 5 , 10 ) );  // Output:  “world”

 

// substr – Start trimming after the 5th character and cut next 10 characters

console.log(  text.substr( 5 , 10 ) );  // Output: “world is a”

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s