JavaScript substring() Method-Javascript Example substring()


The Javascript substring() method extracts the characters from a string, between two specified Charecter positions in string, and returns the new sub string.Javascript String - substring() Method : Learning Javascript in simple and easy steps. A beginner's tutorial containing complete knowledge of Javascript Syntax .

Javascript substring()  syntax : 

String.substring( from [, to ] )

This Javascript substring() method extracts the characters from a string between "from" and "to ", not including "to" itself.

Some Notes about Javascript  Substring() Method:

If 'from' equals 'to', it returns an empty string.
If 'to' is omitted, it extracts characters to the end of the string.
If either argument is less than 0 or is NaN, it is treated as if it were 0.
If either argument is greater than string’s length, either argument will use string’s length.
If from >to, then substring will swap those 2 arguments.


Example of Javascript substring() Method :-


<script>

var str="Hello Javascript substring method";
document.write(str.substring(3,3)+"<br />");
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,0)+"<br />");
document.write(str.substring(3,7)+"<br />");
document.write(str.substring(7,3)+"<br />");

</script>

The output of the code above will be:

empty string
lo Javascript substring method
Hel
lo J
lo J


Tags: ,

Join Us!