Super Javascript
Home About RSS Guest Blogging 🐍 Snake

Javascript Substring

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.

JavaScript
0123456789

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'

Summary

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.

While you are here…

You like retro? Grab my free guide where I will take you step by step to make a classic arcade game in JS.

There are 8 chapters and I will send you a chapter per week by email:

  • Introduction to Snake
  • The Canvas: Your Portal To Pixel Perfect Drawing
  • Setting up a game loop
  • Keeping track of your snake
  • Responding to player’s key presses
  • Enforcing the rules of the game
  • Snake Food
  • Finishing up

To get the game subscribe below:

Want to have a quick play? Click on the game below, press X to start and use the arrow keys to move...