JavaScript String.substring() Method
-
Syntax of JavaScript
string.substring(): -
Example Codes: Use the
string.substring()Method to Extract a Substring From the Reference String -
Example Codes: Use the
string.substring()Method With thestartandendParameters
The string.substring() method creates a substring by taking characters from two positions of the given string. The substring() method can either use the full string from the starting position or extract some characters based on the value added in the start and end parameters.
Syntax of JavaScript string.substring():
referenceString.substring(start);
referenceString.substring(start, end);
referenceString.substring(end, start);
Parameters
start |
It is the position of a given string from where some parts will be extracted to create a substring. The first character will be omitted if the start parameter contains 1. |
end |
To determine the end position of the string that can be used for extraction. The index number of end parameters is always more than the start parameter. |
Return
It returns a substring after extracting the characters of a given string based on the value provided in the start and end parameters.
Example Codes: Use the string.substring() Method to Extract a Substring From the Reference String
The string.substring() method takes the number with less value as the start parameter to determine the position from where the extraction will begin. If only one parameter is used in the string.substring() method, it is considered the start parameter.
In this example, we have passed a single parameter in the string.substring() method.
let newString = 'Hello World! ';
let regE = newString.substring(7);
console.log(regE);
Output:
orld!
Example Codes: Use the string.substring() Method With the start and end Parameters
If we pass two parameters, the second parameter value is considered the end parameter in the string.substring() method. It extracts the substring based on the start and end parameters. In the example below, we have passed different values in the start and end parameters to see the output.
let newString = 'Hello World! Welcome to everyone!';
let str = newString.substring("6", "22");
let ref = newString.substring("21", "4");
console.log(str);
console.log(ref);
Output:
World! Welcome t
o World! Welcome
The string.substring() method creates a substring by taking some parts from the given string.
Although string.substr() and string.substring() are similar, both methods work differently. The string.substring() method determines the start parameter depending on the parameter with less value.
