JavaScript substring vs. substr with Examples

JavaScript substring() Method

JavaScript substring is used to take a part of a string. The syntax of JavaScript substring method is given below:

stringObjectToTakeAPartOf.substring(start-index,stop-index)

  • start-index: (Required – Numeric Value) – where to start the extraction
  • stop-index: (Optional – Numeric Value) – where to stop the extraction
Notes about Javascript substring:
  • If start-index is equal to stop-index, JavaScript substring returns an empty string.
  • If stop-index parameter is omitted, JavaScript substring extracts characters from start-index to the end of the string.
  • If parameters are 0or NaN, the parameters are threated as 0.
  • If parameters are greater than the string’s length, the parameters qill use string’s length.
  • If start-index > stop-index, then the JavaScript substring function swaps 2 parameters.
substring Example:
<script type=”text/javascript”>

var str = “Hello World”;
document.write(str.substring(4,8));

</script>

The output of the above code is:

o wo

—————————————————————————————————–

JavaScript substr() Method

The JavaScript substr() method works slightly different. Instead of the second parameter being an index number, it gives the number of characters. The syntax of JavaScript substr() is given below:

stringObjectToTakeAPartOf.substr(start-index,length)

  • start-index: (Required – Numeric Value) – where to start the extraction
  • length: (Optional – Numeric Value) – how many characters to extract
Notes about substr:
  • To extract characters from the end of the string, use a negative start-index. (Internet Explorer returns the whole string which is wrong.)
  • If the length parameter is omitted, JavaScript substr method extracts to the end of the string.
  • substr() is not supported by Netscape 2, Netscape 3, Internet Explorer 3 and Opera 3.
JavaScript substr Example:
<script type=”text/javascript”>

var str = “Hello World”;
document.write(str.substr(4,4));

</script>

The output of the above code is:

o wo

Since JavaScript substr() is not cross-browser, I never use it.

(Source: bloggingdeveloper dot com) 

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

%d bloggers like this: