JavaScript substring() method retrieves the characters between two indexes and returns a new substring. substring method doesn’t replace the original string.
Contents
- 1 What is Javascript substring method?
- 2 General syntax of substring method
- 3 Extracting from specific position from the string
- 4 To extract the first character from the String
- 5 To extract the last character from the String
- 6 substring vs substr
- 7 Extract substring using regular expression(regex) pattern
What is Javascript substring method?
JavaScript substring() method retrieves the characters between two indexes and returns a new sub string.
General syntax of substring method
string.substring(start, end)
start : Its the starting position where to start the retrieval, first character is at index 0. This parameter is mandatory.
end : Its the position till end of extraction (i,e position up to, but not including). It’s an optional parameter.
Note: JavaScript substring() method doesn’t switch/replace the original string.
Following are some of the substring Examples.
Extracting from specific position from the string
var mystr = "Hello Substring!";
var result = mystr.substring(5);
console.log(result);
Result/Output
Substring!
To extract the first character from the String
var mystr = "Welcome Substring!";
var result = mystr.substring(0, 1);
console.log(result);
Result/Output
W
To extract the last character from the String
var mystr = "Welcome Substring";
var result = mystr.substring(16, 17);
console.log(result);
Result/Output
g
You May Also Like,
substring vs substr
substring considers starting index and ending index. whereas, substr considers starting index and length of characters. Also the starting index (first argument) of substr method can be a negative integer.
Extract substring using regular expression(regex) pattern
Following example illustrates extracting a substring using regular expression.
var mystr = "abcdefsd22j";
var result = mystr.match(/a(.*)j/);
console.log(result[1]);
Result/Output
bcdefsd22
slice method Vs substring method?
Both functions are pretty similar in their syntax, but different in some aspects. Let’s go through the differences.
Common for both methods:
If start argument equals stop argument, then method returns an empty string.
If stop argument is omitted, then method extracts the characters to the end of the string.
If either of the argument is greater than the string’s length, then the string’s length will be considered instead.
Distinctions of substring() method:
If start > stop, then the substring method will swap the respective 2 arguments.
If either of the argument is negative or is NaN, then it is considered as if it were 0.
Distinctions of slice() method:
If start > stop, then the slice method will return an empty string(“”).
If start is negative then thn the method sets char from the end of string.
Want to deep dive into JavaScript programming history, you can check this outstanding JavaScript wiki.