Substrings in Javascript with substring()Substrings in Javascript with substring()

Posted July 24th, 2009 in Javascript

There are two ways to get substrings using Javascript using the string object's substr() (deprecated, and covered in an earlier post) 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. According to my O'Reilly Javascript book substr() is deprecated so use substr() with caution. I personally find the substr() function easier to use the substring().

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus