# I don't understand how a string work

#1

I don’t understand why the loop should end when “j” reach the same value of myName.length +1. Precisely I’m missing why the +1.

I also don’t understand why j have to start at the same value of i.

``````for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);

``````

Marco

#2

Hi @xantrac,

Let’s say, your name is ‘xantrac’

``````var myName = 'xantrac';

var text = 'Random string with xantrac in it';
``````

The first loop, we need loop through the whole string in `text` to find ‘xantrac’, particularly any word that starts with ‘x’

Then comes the part, which is what you’re asking:

``````for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
``````

This second loop is to loop through myName, which is the whole ‘xantrac’ word.
Take note ‘xantrac’ has 7 characters in it.

So these two loops work like this:

``````First loop, i = 0, loop through the whole string in var text

text      : Random string with xantrac in it
||||||||||||||||||||
text[i] =   01234..............19

at position 19, which is text[i] = text[19], i = 19, we found the letter 'x'
``````

Then comes the second loop:

``````Second loop,j = i, i = 19, mean j = 19, loop through var myName.length (7 characters)

myName    : xantrac
|||||||
text[j] =  19.....25

at position 25, text[j] = text[25], j = 25, we finish looping the name length equivalent to 'xantrac'
``````

So by dissecting this part:

``````j < (myName.length + i)
``````

myName.length = 7
What about `i` ? i equals to 19 (when you first found ‘x’ at position 19)

That makes:

`j < (7+ 19)`
`j < 26`
j++ will stop after position-25 because the < sign, 25 is < than 26.

Conclusion:

Why `j` needs to begin with the number of `i`:

• Because it needs to start at position-i, so:
``````hits.push(text[j]);
``````

You’d to push text[19], text[20], text[21]… till text[25].

Why `myName.length + i`:

• Because if you write `myName.length` without the `+i`, the second loop will not run since `j < 7` when `j = 19`, j starts at 19.

Hope this clears your doubt. Cheers

#3

Thank you @codexthon !
Your explanation is extremely clear, to be honest I would never get to that solution by my self.

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.