Home Tutorials RSS

Javascript Substring

JavaScript has superb string and text handling facilities, from basic string handling functions to ‘regex’ which allows you to do sophisticated find and replaces on your strings.

One of the more basic functions is substring which takes a string and returns a specific part of that string.

The substring function takes two arguments, The first is the position to start extracting the string, and the second is the position to stop extracting the string.

Below is some text with the positions marked. Positions, like array indexes in Javascript, start at zero.


If I were take a substring from 2 to 4, I would get va, This is because there is a v at position 2, a a at position 3, and then we stop just before position 4.

In code this might look something like this;

var str = `Javascript`;
var sub = str.substring(2, 4);

You can also leave off the second argument to get the string all the way to the end. For example this code:

var str = `Javascript`;
var sub = str.substring(2);

Would give the result in sub being set to 'vascript'.

What if the first number is out of range, for example it is a negative number of beyond the last character in the string?

Rather than just throw an error, Javascript will do it’s best. For a negative number it is treated like a zero. For a number beyond the end of the string, you will always get an empty string result.

It has similar defaulting for the second argument. If you are interested, have a play in a Javascript console to see how that behaves.

Using “length” with Javascript substring

A handy property to use in conjunction with substring is length. This simply tells us how long the string is, for example:

var str = 'Javascript';
var len = str.length; // result is 10

The index of the last character in a string is the length minus 1 (because we start at zero). This means we can get the last character like this:

var str = 'Javascript';
var last = str.substring(str.length - 1); // result is 't'


This is a brief tutorial on Javascript Substring. As a programmer it is something you will use quite a lot. Most programming languages have a built in function like substring, so whatever you are programming you are sure to bump into it sooner or later.

See Also