JavaScript substring() method
stringObject.substring(start,stop)
Definition and Usage
The substring() method is used to extract characters in a string between two specified subscripts.
illustrate
The substring returned by the substring() method includes the characters at start but not the characters at stop .
If the parameters start and stop are equal, then the method returns an empty string (that is, a string of length 0). If start is greater than stop , the method swaps the two parameters before extracting the substring.
Tips and Notes
Important: Unlike the slice() and substr() methods, substring() does not accept negative arguments.
JavaScript substr() method
stringObject.substr(start,length)
start | Required. The starting subscript of the substring to extract. Must be a numeric value. If negative, the parameter specifies the position from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second-to-last character, and so on. |
length | Optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, the string from the beginning to the end of stringObject is returned . |
return value
A new string containing length characters starting at start of stringObject (including the character pointed to by start) . If length is not specified , then the returned string contains the characters from start to the end of stringObject .
Tips and Notes
Note: The arguments to substr() specify the start position and length of the substring, so it can be used in place of substring() and slice().
Important: ECMAscript does not standardize this method and therefore deprecates its use.
Important: In IE 4, the value of the parameter start is invalid. In this BUG, start specifies the position of the 0th character. In later versions, this bug has been fixed.
Example 1
In this example, we will use substr() to extract some characters from the string:
<script type="text/javascript"> var str="Hello world!" document.write(str.substr(3)) </script>
output:
lo world!
Example 2
In this example, we will use substr() to extract some characters from the string:
<script type="text/javascript"> var str="Hello world!" document.write(str.substr(3,7)) </script>
output:
lo worl (space counts as one character)
Example 3
In this example, we will use substr() to extract some characters from the string:
<script type="text/javascript"> var str="Hello world!" document.write(str.substr(-5,1)) </script>
output:
o (negative numbers are truncated from the back)
Example 4
In this example, we will use substr() to extract some characters from the string:
<script type="text/javascript"> var str="Hello world!" document.write(str.substr(-5)) </script>
output:
orld!