JavaScript substring() method retrieves the characters between two indexes and returns a new sub string.substring method doesn’t replace the original string.

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 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

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)

var mystr = "abcdefsd22j";

var result = mystr.match(/a(.*)j/);

console.log(result[1]);

Result/Output

bcdefsd22

check out more Javascript methods like split string.

Want to deep dive into JavaScript programming history, you can check this outstanding JavaScript wiki.

Pin It on Pinterest

Share This