When you write JavaScript, you need to know what string manipulation methods/functions are available. In the previous posts JavaScript substr Function and JavaScript substring Function, we gave examples on usages of the two most common javascript string functions. You can also find the details below:
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.
Want automatic updates?
Subscribe to our RSS feed
or
Get Email Updates
sent directly to your inbox!
Currently rated 4.0 by 17 people
- Currently 4/5 Stars.
- 1
- 2
- 3
- 4
- 5