Thursday, May 8, 2008

JavaScript substring vs. substr

The Difference Between JavaScript String Extraction Functions
When you write JavaScript, you need to know what string manipulation methods/functions are available.

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.
* substr() is not cross-browser.

JavaScript substr Example
<script type="text/javascript">

var str = "Hello World";
document.write(str.substr(4,8));

</script>

The output of the above code is:
o wo

No comments: