Substring() , Substr() and Slice()

Javascript String Substring

In Javascript, you can extract the portion of a string from a larger string through one of following methods. They are string.substring(), string.substr() and string.slice().

Substring()

Javascript string substring() method extracts the characters from a larger string based on character indexes and returns the new sub string.

Syntax

startIndex : An integer value representing where to start the extraction.

endIndex: An integer value representing the position up to end the extraction, the endIndex value is not included in the returned substring. (that is endIndex value -1). This endIndex is optional, if it is omitted, the method will extract it extracts the rest of the string from startIndex.

The above code will return "string" that is it extract from the position 10 and upto 16 (16-1, because endIndex is not included).

More Javascript substring examples

The above code will return "string", because the startIndex is greater than endIndex, it will swap the values.

It will return only one character, that is "g".

It will return "is a string", it will extract from the position 5 to end of the string because endIndex is omitted.

It will return "This" , it will extract first 4 characters because start index is 0.

It will return "This is a string", if the startIndex is less than 0 (zero), it will extract from the index position 0 (zero).

Substr()

Javascript String Substr()

Javascript string substr() method accept two arguments and return a new string. The first argument is the index position and second argument is length. The substr() method extract a new string from the start index position and number of characters specified in the length parameter.

Syntax

example

It will return "string", that is it extract from the position 10 and extract 6 characters.

More substr() examples

It will return "is a string" , it will extract from the position 5 and up to end of the string, because the length argument is missing.

Slice()

Javascript String slice() method extracts the characters from startIndex to endIndex

Syntax

Javascript String startIndex

startIndex : An integer value representing where to start the extraction.

endIndex: An integer value representing the position up to end the extraction, the endIndex value is not included in the extracted string. (that is endIndex value -1). This endIndex is optional, if it is omitted, the method will extract it extracts the rest of the string from startIndex.

It will return "string", that is , extract from the startIndex position and upto endIndex position -1 (endIndex value is not included).