Checking past the first letter of your name


#1

Absolute beginner here, in the end my main piece of code looks like this:

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

It does what it's supposed to and lets me pass the test, but I want to improve the code by also having it check the rest of the letters of the myName variable. I first thought of this alteration of the first if-statement:

if (text[i] === myName[0] && text[i+1] === myName[1] && text[i+2] === myName[2] && text[i+3] === myName[3] && text[i+4] === myName[4] etc... ) {

I dismissed it because it looks messy and I don't like solving it this way. I want to do it using another loop, or maybe even a function. But how do I go about this? I'm only asking for a push in the right direction, I really want to write the code myself.


#2

@tripletth,
Before going into the second FOR-loop
you could define a variable collectText
var collectText = "";

Then in your second FOR-loop
you could make use of JavaScript's string concatenation facility
by concatenating every text[ j ] onto collectText
collectText += text[ j ]

Then after leaving the second FOR-loop
you could use a =strict= comparison, to compare collectText with myName

if ( collectText === myName ) {
      //IF code-block
}

Reference

google search
== the Book ==
javascript [your question] site:developer.mozilla.org

== discussions / opinions ==
javascript [your question] site:stackoverflow.com

== guidance ==
www.crockford.com
http://javascript.crockford.com/code.html
http://javascript.crockford.com/survey.html
= http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
www.developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
= http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1

Code-Year
https://www.codecademy.com/en/tracks/code-year?jump_to=4fce4211279bae0003006265

teach yourself javascript site:codecademy.com
https://www.codecademy.com/en/tracks/teachyourself
Meet JSON
https://www.codecademy.com/courses/javascript-beginner-en-xTAfX/0/1?curriculum_id=50802b7d5225bf0200000767
Adding Event Handlers The Simple Way
https://www.codecademy.com/courses/web-beginner-en-A0uwI/0/1?curriculum_id=50802b7d5225bf0200000767
JavaScript and Cookies
https://www.codecademy.com/courses/javascript-beginner-en-5knNv/0/1?curriculum_id=50802b7d5225bf0200000767
Dealing with the DOM
https://www.codecademy.com/courses/javascript-beginner-en-gwcYv/0/1?curriculum_id=50802b7d5225bf0200000767
JavaScript and CSS
https://www.codecademy.com/courses/web-beginner-en-SEgtM/0/1?curriculum_id=50802b7d5225bf0200000767

Yourself Python: http://www.codecademy.com/courses/python-beginner-en-fymF4


#3

Thanks a lot! It took me a while, but I figured it out!