The JavaScript Substring method allows to extract or cut out a piece of text from the input string. The method has two input parameters “start position” and “end position“. The “start position” parameter is requited and if the “end position” is missing the method takes all way up to the end of string. The syntax of JavaScript Substring is following:
<string_variable>.substring(<start_position>,<end_position>);
On this first JavaScript example below we are declaring a string variable named my_text and we will assign to it value “JavaScript Online Course“. On the following line in the example will cut off the first 11 letter using the JavaScript Substring and the result becomes “Online Course“.
<html> <body> <h2>My JavaScript Substring Example 1</h2> <script type="text/javascript"> var my_text = "JavaScript Online Course"; document.write("<p>"+my_text.substring(11)+"</p>"); </script> </body> </html>
You can try this example on this link.
To set as well the end position use the position number in the main string as on the following example. It removes the “Course” word from the end leaving only word “Online“.
<html> <body> <h2>My JavaScript Substring Example 1</h2> <script type="text/javascript"> var my_text = "JavaScript Online Course"; document.write("<p>"+my_text.substring(11,17)+"</p>"); </script> </body> </html>
You can try this example on this link.
See Also:
Home