Home / Substrings in Javascript with substring()

Substrings in Javascript with substring()

There are two ways to get substrings using Javascript using the string object's substr() and substring() functions. You could also extract a string using a regular expression but I'll cover that in another post.

String.substring(start, to)

substring() takes two arguments, although the second can be omitted:

start: the position to start extracting the string from. The first character is 0, the second is 1 and so on. If it's a negative value then 0 is used instead.

to: The position to copy to and should be greater than start. Note that the string returned will be from start to to-1, which can be a little confusing because it does not include the character at to. If to is the same as start then nothing will be returned. If to is omitted then the rest of the string from from 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"

String.substr(start, length)

String.substr is covered in another post. I personally find the substr() function easier to use the substring().