Knowing how to manipulate strings can become one of the most helpful tools in your bag of tricks in the wonderland known as JavaScript. One of the Methods we can use that we will be discussing here today is called the Substring Method.

The Substring Method in JavaScript can also be applied to Visual Basic, as well as Visual C Sharp, C#. What the Substring Method does is it allows you to take sections a.k.a. parse, whether its singular words or full phrases, and create a new string or unleash your will upon it. Using this in conjunction with the IndexOf Method will let you find  where the variable, section of the string you are looking for, is located.

Let begin with a quick example. Let’s take the string, “Do I love pie?” and answer the question.

Now let’s break down what we have done in this bit of code. First we are declaring a variable “s” which is our string. Next we have a variable “w” that will contain a string, the letter “I” in our case, that we will be looking for. Now, what we do next is search for the IndexOf variable “w”, which is three. We will then use this as a starting point for our Substring Method to begin, which we named “ns”, and then use the length of our original string “s” minus one as an ending point. The reason we subtracted one from the original string length is so we do not include the question mark in our new string, “ns” and then add a period to complete our new string.

I have then also put in an alert to help you understand what steps are taking place. This alert will display the IndexOf “w” in our original string.

And lastly, we will be writing our new string to the body of our HTML document.

You have now learned how to parse out a section of a string and manipulate it to do whatever you please, in this case, answer a question in code!

If you still feel a bit confused or don’t understand the subject matter, please don’t hesitate to download the Source Code provided at the bottom. I have included some other examples as well to help illustrate some other possibilities of the Substring Method. Thank you for joining me and I hope you have found this useful. Take care and until next time.

Download Source Files