JavaScript: String substring() method
This JavaScript tutorial explains how to use the string method called substring() with syntax and examples.
Description
In JavaScript, substring() is a string method that is used to extract a substring from a string, given start and end positions within the string. Because the substring() method is a method of the String object, it must be invoked through a particular instance of the String class.
Syntax
In JavaScript, the syntax for the substring() method is:
string.substring(start_position [, end_position]);
Parameters or Arguments
- start_position
- The position in string where the extraction will start. The first position in string is 0.
- end_position
- Optional. It determines the position in string where the extraction will end (but does not include the character at end_position in the extracted substring). The first position in string is 0. If this parameter is not provided, the substring() method will return all characters to the end of the string.
Returns
The substring() method returns a substring that has been extracted from string given the start_position and end_position.
Note
Example
Let's take a look at an example of how to use the substring() method in JavaScript.
For example:
var totn_string = 'TechOnTheNet';
console.log(totn_string.substring(0,4));
console.log(totn_string.substring(4,6));
console.log(totn_string.substring(6,9));
console.log(totn_string.substring(9,12));
In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the substring() method of the totn_string variable to extract the substring from the string.
We have written the output of the substring() method to the web browser console log, for demonstration purposes, to show what the substring() method returns.
The following will be output to the web browser console log:
Tech On The Net
As you can see, the substring() method returned 'Tech' for the first call, 'On' for the second call, 'The' for the third call and 'Net' for the fourth call.
Advertisements