This JavaScript tutorial explains how to use the string method called substring() with syntax and examples.
Description
In JavaScript, substring() is a string technique that is used to extract a substring from a string, given start and stop positions within the string. Because the substring() approach 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() approach is:
string.substring(start_position [, end_position]);
Parameters or Arguments
start_position The role in string the place the extraction will start. The first position in string is 0. end_position Optional. It determines the function in string the place the extraction will cease (but does not consist of the character at end_position in the extracted substring). The first function in string is zero If this parameter is not provided, the substring() method will return all characters to the quit of the string.
Returns
The substring() method returns a substring that has been extracted from string given the start_position and end_position.
Note
The substring() method does not exchange the price of the authentic string. See also the slice() and the substr() methods.
Example
Let’s take a look at an instance 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 known as totn_string that is assigned the string price 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() approach to the net browser console log, for demonstration purposes, to exhibit what the substring() technique returns.
The following will be output to the web browser console log:
Tech
On
The
Net
As you can see, the substring() method back ‘Tech’ for the first call, ‘On’ for the 2nd call, ‘The’ for the 0.33 name and ‘Net’ for the fourth call.
Leave a Review