JavaScript String.substr() Method
-
Syntax of JavaScript
string.substr(): -
Example Codes: Use the
string.substr()Method to Extract Parts of a String -
Example Codes: Use the
string.substr()Method to Limit the Characters for the New Substring
The String substr() method is a legacy function used to create a new string by taking some parts of the given string. A substr() method can limit words that will be taken into substring from the original string by defining the start and length.
Syntax of JavaScript string.substr():
referenceString.substr(start);
referenceString.substr(start, length);
Parameters
start |
It denotes the position of a string from where the extraction for the substring will start. The first string character is at index 0. |
length |
To determine how many characters will be added in the substring. If the number is 5, only 5 characters will be extracted from a string. |
Return
It returns a substring that includes some parts of the original string based on the start and length parameters.
Example Codes: Use the string.substr() Method to Extract Parts of a String
The JavaScript string.substr() method uses the start parameter to determine the position of the given string from where the characters need to be extracted. Since it is a legacy function, the start parameter can be used to define the starting characters.
In the example below, we have passed the start parameter in the string.substr() method with different values.
let str = 'Hello World! ';
let regE = str.substr(-4);
let arr = str.substr(4);
console.log(regE);
console.log(arr);
Output:
rld!
o World!
Example Codes: Use the string.substr() Method to Limit the Characters for the New Substring
We can determine how many words can be extracted from the original string using the length parameter in the string.substr() method.
In the example below, we have passed the length parameter after the start parameter. In the output, the number of characters is the same as we mentioned in the length parameter.
let str = 'Hello World! Welcome to everyone!';
let arr = str.substr("7", "9");
let ref = str.substr("12", "13");
console.log(arr);
console.log(ref);
Output:
orld! Wel
Welcome to e
The string.substr() method extracts parts of a string and creates a substring in JavaScript.
Both string.substr() and string.substring() methods are used for similar purposes but work differently. While the length parameter in the substr() method specifies the number of characters, the end parameter in the substring() method chooses the end index of a string.
