Substrings in Javascript with substring()

How to use String.substring(start, to)

The old method substr() is deprecated so screw that. The preferred method is to now use substring().

(start,to) arguments explained:

start – This is the position to start extracting the string from.   Zero based, so the first character is 0, then 1 and so on.

to – This is the position to copy to and should obviously be greater than start.   It does not include the character at to. So, if to is the same as start then nothing will be returned. If to is not present then the rest of the string from start is returned.

The examples below use the following string.

var s = "abcdefghij"

The first example returns the characters from positions 5 to 6. Remember that the string is zero indexed so the character at position 5 in the above string is “f”

s.substring(5, 7); // returns "fg"

The second example returns the characters from 5 to the end of the string:

s.substring(5); // returns "fghij"

The next example returns the characters from positions 0 to 4 (i.e. 5 characters in total):

s.substring(0, 5); // returns "abcde"
Advertisements