↑ Grab this Headline Animator

Thursday, November 13, 2008

Difference Between substring and substr in javascript?


The functionality of the substring is Extracts the part of the string from the string.

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

Where start-index will start from 0
and stop-index will start from 1 Like

Example: In the string "Hello World" if we want "o Wo" then in the substring function we will give start-index as 4 means count from 0(position of the H) to 4 and stop-index will be 8 means count from 1(position of the H) to 8.

start-index: (Required - Numeric Value) - where to start the extraction
stop-index: (Optional - Numeric Value) - where to stop the extraction

Notes about Javascript substring:

1.If start-index is equal to stop-index, JavaScript substring returns an empty string.

2.If stop-index parameter is omitted, JavaScript substring extracts characters from start-index to the end of the string.
3.If parameters are 0or NaN, the parameters are threated as 0.
4.If parameters are greater than the string's length, the parameters qill use string's length.
5.If start-index > stop-index, then the JavaScript substring function swaps 2 parameters.


The functionality of the substr is Extracts the number of character from the string
Syntax: stringObjectToTakeAPartOf.substring(start-index,length)

start-index: (Required - Numeric Value) - where to start the extraction(from position 0)
length: (Optional - Numeric Value) - how many characters to extract

Notes about substr:
1.To extract characters from the end of the string, use a negative start-index. (Internet Explorer returns the whole string which is wrong.)
2.If the length parameter is omitted, JavaScript substr method extracts to the end of the string.
3.substr() is not supported by Netscape 2, Netscape 3, Internet Explorer 3 and Opera 3.

Example:Take an example in the javascript

<script type="text/jscript" language="javascript">

function Test()
var str="Hello World";


The above answer will be
1.first alert will return empty space
2.second alert will return "ll" value.

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.


Latest Articles