Let begin with a quick example. Let’s take the string, “Do I love pie?” and answer the question.
var s = "Do I love pie?";
var w = "I";
var index = s.indexOf(w);
ns = s.substring(index, s.length -1) + "." ;
document.body.innerHTML = ns;
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.