Substrings in Javascript with substr()

Posted in Javascript -

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.substr(start, length)

substr() 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. It can be negative in which case it starts from the end of the string where -1 is the last character, -2 is the second to last character and so on.

length: the number of characters to extract from the string. If it's omitted then all characters from start to the end of the string will be included. If it is bigger than the number of remaining characters in the string then (obviously) just the remaining characters will be returned.

The examples below use the following string. I've used numbers so it's easy to see what's going on.

var s = "1234567890";

Get all the characters in the string from the 8th (i.e. start = 7, because it's zero based):

s.substr(7); // returns 890

Get the first two characters from the string:

s.substr(0, 2); // returns 12

Get the last two characters from the string:

s.substr(-2); // returns 90

Get four characters starting from the 4th (i.e. start = 3):

s.substr(3, 4); // returns 4567

If start + length is greater than what's remaining in the string then only the characters to the end of the string included (obviously there isn't anything else to extract) so the resulting string may not be necessarily as long as what you are expecting. This is illustrated in the following example where length passed is 20 but the resulting string is only 4 characters long:

s.substr(6, 20); // returns 7890

Get two characters starting 4 from the end:

s.substr(-4, 2); // returns 78

String.substring(start, to)

String.substring() works slightly differently to String.substr() where the start and to positions are passed as arguments instead of start and length. I will cover this function in my Javascript post on Friday.



Related posts:


Comments