47
Substring and stuff with JavaScript
A string is a thin wire, you used to hang your clothes to dry. Just kidding !
A string in computer terms is a sequence of characters, we use strings to represent words or a sequence of characters in programming. Here's an example for a string,
A string in computer terms is a sequence of characters, we use strings to represent words or a sequence of characters in programming. Here's an example for a string,
A substring is nothing but a string inside a string. But remember, substrings are contiguous!. If it isn't clear, don't worry, we'll get it right. Have a look at the below gist.
Let a given string has a length of 5, let us take it as a variable
n
, then the total number of possible substrings is given by,Total possible substrings = n*(n+1)/2
for example, let us take
n
as 5 as we assumed above, then5*(5+1)/2
which turns into (5*6)/2
, eventually yields the value of 15
(which is the total number of possible substrings for a string of length 5). ⚡Note:
Notice that the substrings are contiguous, notice how
Notice that the substrings are contiguous, notice how
wa
or wd
are not substrings of wsad
. Only adjoining sequence characters are taken from the string, and are called as substrings.Now take a deep breath, we are going to dive into the JavaScript ocean🥽
So, let us look at the JavaScript code step-by-step for printing (I mean console logging) all the substrings for a given string.
Let us start by initializing the input string and the length of the input string.
Let us start by initializing the input string and the length of the input string.
FindSubstring
for
for
i
0 to <n
for
j
i to <n
for
Now, after determining the starting and ending point of the input string, we use a third
for
loop to console log
the sequence of characters from starting point to ending point. For that, we loop using iterator k
from i to <j+1. Inside the loop we console log
the sequence of characters as follows,We use
charAt
method above to pass in the string index, i.e k
.Not until we call our
FindSubstring
function and pass it both inpstring
and n
values. Let us do that to wrap it up,You can also take a look at this JSFiddle to change input strings to your wish.
Feel free to correct me if I am wrong, give a 💖 if you like the content. Thanks for reading and have a nice day.
Cover image : Photo by Timothy Muza on Unsplash
47