www.webdeveloper.com
Results 1 to 7 of 7

Thread: javascript code not doing what I want (noob question)

  1. #1
    Join Date
    May 2014
    Posts
    3

    Post javascript code not doing what I want (noob question)

    Hello my dear friends!

    I am new to the world of JavaScript (2 days only), but I have some experience with other programming languages. I am currently following the javascript tutorial found on codeacademy to get an overview of this language and I'm planning on searching other tutorials later. Today, I needed to do an exercise where the script finds my name in a big text and push the letters of my name in an array named "hits". I followed the instructions of the website. The way it's working is that it searches the first letter of my name (A for Andrew) and pushes the letters in the array. As you expect, other words get into the array because they also start with a capital A.
    Code:
    /*jshint multistr:true */
    var text=" Ex placerat senserit nam, at perpetua \
    cotidieque sit. Ut mei iudicabit forensibus. Pro et copiosae fabellas, per vivendum \
    efficiantur no. Dicam interesset vel ut, et est tota error invidunt. \
    Mel ea minim ancillae, odio populo ullamcorper mea id, ne sea doming \
    persequeris definitiones. Duo te invenire laboramus, eum eruditi \
    impedit ex. Nullam libris quaestio pro id. Sea solum timeam fuisset \
    at, verear periculis vel eu, rebum efficiantur vis ei. Ut nibh autem \
    eruditi sed, mea agam omnis illum ei. Ius elitr \
    iudico democritum ut, eam error dolorum conceptam ad, solet virtute \
    delicatissimi eos at.Natum tation nominavi vix ne, putent \
    omnesque Andrew sapientem duo in. Ne duo modus dicant explicari, \
    invidunt tacimates pro ei. Ea duo sonet fierent. No quem suas nec, sensibus \
    mediocrem ea mea. Facilis civibus perpetua sit id, sit ea melius utamur. Timeam \
    iuvaret mea ex. In postea oporteat eleifend his, ut eripuit senserit est. Commodo \
    Andrew eleifend euripidis eos in, usu et recusabo maluisset patrioque. Soluta \
    deterruisset nec ut. Ei vero velit vitae sea. In pro esse corpora forensibus. \
    Vim iuvaret recteque eu. Cu mea meis magna mundi, facer fuisset scriptorem cu \
    nec. Option accusam similique an vix, velit harum probatus et pro. Pri eius \
    impedit pertinax te. Eu vis ferri conceptam eloquentiam, vis alia solet \
    ne. Audiam placerat salutatus per ex. *** ne omnes ubique elaboraret. Ad quot \
    numquam eligendi qui, elitr fastidii quaerendum eum in, eu quis atqui exerci \
    nam. Cu mea nihil Andrew graecis complectitur, ne *** ferri viderer \
    perpetua. Pro id mucius vidisse docendi, sanctus ancillae nec at, has disputando \
    consectetuer ea. Vim exerci accusamus an, cetero assueverit mea ne. Modo \
    omittam oporteat vim ex, qui nullam sapientem periculis ea, eos ponderum \
    abhorreant ex. Tation mentitum ut est, suscipit assentior an ius, eripuit \
    aliquam mandamus sed an. Eam purto zril libris ex, ei esse virtute nam, \
    ne modus meliore nec. Mel eius nobis petentium an, eum cetero delicatissimi eu. His ea ridens voluptatibus. Possim perfecto philosophia pri et, viris tibique pri \
    id. Commune signiferumque no per, laoreet corpora expetendis sit no. Putent \
    aeterno ponderum ei vim, nec quidam corrumpit ut. Sed ex aliquam verterem accusamus, \
    his causae molestie vivendum ei. Has cu sumo contentiones, pri principes \
    adipiscing ne. Andrew Porro fierent mediocritatem his an, usu id nihil \
    adipiscing complectitur. Cu ludus gubergren duo, te eos soluta altera eligendi. \
    Id rebum expetenda ius. Ancillae petentium laboramus pro cu, an quo nibh \
    etiam, consul alienum constituto his an. An malis euismod eam, sea cu \
    ludus regione, nusquam nominavi suscipit in eum. Pro doming aperiri deterruisset \
    ex, usu ex laboramus intellegam, sit fastidii partiendo cotidieque \
    ex. Solet aliquip prodesset vel eu, ipsum torquatos an sed.";
    var myName="Andrew";
    var hits=[];
    for(i=0;i<text.length;i++){
        if(text[i]==="A"){
            for(var j=i;j<myName.length+i;j++){
                hits.push(text[j]);
            }
        }
    }
    if(hits.length===0){
        console.log("You name wasn't found!");
    }else{
        console.log(hits);
    }
    I tried to push the exercise further and tell my script to erase the letters that are not my name with the splice function. Here is the code I added at the end:
    Code:
    for(k=1;k<hits.length;k+=myName.length){
        if(hits[k]!==myName[1]){
            hits.splice(k-1,myName.length);
        }
    }
    This code does erase values from the array, but instead of keeping my name many times the result is only random letters. I understand the problem is from the last 3 lines but I can't find a workaround. I do understand I lack knowledge to be able to find a solution. I searched on the internet but I couldn't solve this code.

    I would really appreciate your help to become a better programmer!

    Thanks in advance!

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,377

    Lightbulb

    Consider this modification...
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> HTML5 page </title>
    
    </head>
    <body>
    <script type="text/javascript">
    
    var txt=" Ex placerat senserit nam, at perpetua \
    cotidieque sit. Ut mei iudicabit forensibus. Pro et copiosae fabellas, per vivendum \
    efficiantur no. Dicam interesset vel ut, et est tota error invidunt. \
    Mel ea minim ancillae, odio populo ullamcorper mea id, ne sea doming \
    persequeris definitiones. Duo te invenire laboramus, eum eruditi \
    impedit ex. Nullam libris quaestio pro id. Sea solum timeam fuisset \
    at, verear periculis vel eu, rebum efficiantur vis ei. Ut nibh autem \
    eruditi sed, mea agam omnis illum ei. Ius elitr \
    iudico democritum ut, eam error dolorum conceptam ad, solet virtute \
    delicatissimi eos at.Natum tation nominavi vix ne, putent \
    omnesque Andrew sapientem duo in. Ne duo modus dicant explicari, \
    invidunt tacimates pro ei. Ea duo sonet fierent. No quem suas nec, sensibus \
    mediocrem ea mea. Facilis civibus perpetua sit id, sit ea melius utamur. Timeam \
    iuvaret mea ex. In postea oporteat eleifend his, ut eripuit senserit est. Commodo \
    Andrew eleifend euripidis eos in, usu et recusabo maluisset patrioque. Soluta \
    deterruisset nec ut. Ei vero velit vitae sea. In pro esse corpora forensibus. \
    Vim iuvaret recteque eu. Cu mea meis magna mundi, facer fuisset scriptorem cu \
    nec. Option accusam similique an vix, velit harum probatus et pro. Pri eius \
    impedit pertinax te. Eu vis ferri conceptam eloquentiam, vis alia solet \
    ne. Audiam placerat salutatus per ex. *** ne omnes ubique elaboraret. Ad quot \
    numquam eligendi qui, elitr fastidii quaerendum eum in, eu quis atqui exerci \
    nam. Cu mea nihil Andrew graecis complectitur, ne *** ferri viderer \
    perpetua. Pro id mucius vidisse docendi, sanctus ancillae nec at, has disputando \
    consectetuer ea. Vim exerci accusamus an, cetero assueverit mea ne. Modo \
    omittam oporteat vim ex, qui nullam sapientem periculis ea, eos ponderum \
    abhorreant ex. Tation mentitum ut est, suscipit assentior an ius, eripuit \
    aliquam mandamus sed an. Eam purto zril libris ex, ei esse virtute nam, \
    ne modus meliore nec. Mel eius nobis petentium an, eum cetero delicatissimi eu. His ea ridens voluptatibus. Possim perfecto philosophia pri et, viris tibique pri \
    id. Commune signiferumque no per, laoreet corpora expetendis sit no. Putent \
    aeterno ponderum ei vim, nec quidam corrumpit ut. Sed ex aliquam verterem accusamus, \
    his causae molestie vivendum ei. Has cu sumo contentiones, pri principes \
    adipiscing ne. Andrew Porro fierent mediocritatem his an, usu id nihil \
    adipiscing complectitur. Cu ludus gubergren duo, te eos soluta altera eligendi. \
    Id rebum expetenda ius. Ancillae petentium laboramus pro cu, an quo nibh \
    etiam, consul alienum constituto his an. An malis euismod eam, sea cu \
    ludus regione, nusquam nominavi suscipit in eum. Pro doming aperiri deterruisset \
    ex, usu ex laboramus intellegam, sit fastidii partiendo cotidieque \
    ex. Solet aliquip prodesset vel eu, ipsum torquatos an sed.";
    
    var myName="Andrew";
    var hits=[];
    var tarr = txt.split(' ');
    for (i=0; i<tarr.length; i++) {
      if (tarr[i] == myName) { hits.push(tarr[i]); }
    }
    
    if (hits.length == 0 ){
      alert("You name wasn't found!");
    } else {
      alert('Found '+hits.length+' entries of '+myName);
    }
    </script>
    
    </body>
    </html>

  3. #3
    Join Date
    May 2014
    Posts
    3
    Thank you for your answer! I will study your version of the code!

  4. #4
    Join Date
    May 2014
    Posts
    897
    Uhm... why not just use indexOf?

    https://developer.mozilla.org/en-US/...String/indexOf

    Unless of course, this is a brute force exercise -- but I hate brute force exercises to recreate existing language functionality -- never made a lot of sense to me unless you were using machine language.
    Java is to JavaScript as Ham is to Hamburger.

  5. #5
    Join Date
    May 2014
    Posts
    897
    Oh, and some tips... if you are declaring a bunch of var in a row, you don't need to say VAR each time, you can make a comma delimited list. It might also be more useful to store WHERE in the text they are, not the word.

    Code:
    var
    	txt = "Ex placerat senserit nam, at perpetua \
    cotidieque sit. Ut mei iudicabit forensibus. Pro et copiosae fabellas, per vivendum \
    efficiantur no. Dicam interesset vel ut, et est tota error invidunt. \
    Mel ea minim ancillae, odio populo ullamcorper mea id, ne sea doming \
    persequeris definitiones. Duo te invenire laboramus, eum eruditi \
    impedit ex. Nullam libris quaestio pro id. Sea solum timeam fuisset \
    at, verear periculis vel eu, rebum efficiantur vis ei. Ut nibh autem \
    eruditi sed, mea agam omnis illum ei. Ius elitr \
    iudico democritum ut, eam error dolorum conceptam ad, solet virtute \
    delicatissimi eos at.Natum tation nominavi vix ne, putent \
    omnesque Andrew sapientem duo in. Ne duo modus dicant explicari, \
    invidunt tacimates pro ei. Ea duo sonet fierent. No quem suas nec, sensibus \
    mediocrem ea mea. Facilis civibus perpetua sit id, sit ea melius utamur. Timeam \
    iuvaret mea ex. In postea oporteat eleifend his, ut eripuit senserit est. Commodo \
    Andrew eleifend euripidis eos in, usu et recusabo maluisset patrioque. Soluta \
    deterruisset nec ut. Ei vero velit vitae sea. In pro esse corpora forensibus. \
    Vim iuvaret recteque eu. Cu mea meis magna mundi, facer fuisset scriptorem cu \
    nec. Option accusam similique an vix, velit harum probatus et pro. Pri eius \
    impedit pertinax te. Eu vis ferri conceptam eloquentiam, vis alia solet \
    ne. Audiam placerat salutatus per ex. *** ne omnes ubique elaboraret. Ad quot \
    numquam eligendi qui, elitr fastidii quaerendum eum in, eu quis atqui exerci \
    nam. Cu mea nihil Andrew graecis complectitur, ne *** ferri viderer \
    perpetua. Pro id mucius vidisse docendi, sanctus ancillae nec at, has disputando \
    consectetuer ea. Vim exerci accusamus an, cetero assueverit mea ne. Modo \
    omittam oporteat vim ex, qui nullam sapientem periculis ea, eos ponderum \
    abhorreant ex. Tation mentitum ut est, suscipit assentior an ius, eripuit \
    aliquam mandamus sed an. Eam purto zril libris ex, ei esse virtute nam, \
    ne modus meliore nec. Mel eius nobis petentium an, eum cetero delicatissimi eu. His ea ridens voluptatibus. Possim perfecto philosophia pri et, viris tibique pri \
    id. Commune signiferumque no per, laoreet corpora expetendis sit no. Putent \
    aeterno ponderum ei vim, nec quidam corrumpit ut. Sed ex aliquam verterem accusamus, \
    his causae molestie vivendum ei. Has cu sumo contentiones, pri principes \
    adipiscing ne. Andrew Porro fierent mediocritatem his an, usu id nihil \
    adipiscing complectitur. Cu ludus gubergren duo, te eos soluta altera eligendi. \
    Id rebum expetenda ius. Ancillae petentium laboramus pro cu, an quo nibh \
    etiam, consul alienum constituto his an. An malis euismod eam, sea cu \
    ludus regione, nusquam nominavi suscipit in eum. Pro doming aperiri deterruisset \
    ex, usu ex laboramus intellegam, sit fastidii partiendo cotidieque \
    ex. Solet aliquip prodesset vel eu, ipsum torquatos an sed.",
    
    	searchName = 'Andrew',
    	hits = [],
    	i = 0;
    	
    while (
    	(i < txt.length) &&
    	((i = txt.indexOf(searchName, i)) > -1)
    ) {
    	hits.push(i);
    	i += searchName.length;
    }
    
    console.log(
    	hits.length == 0 ?
    	'Search Name Not Found' :
    	'Found ' + hits.length + ' instances of ' + searchName
    );
    To break it down, checks if our index is less than the length, if so we find the first instance of the search name with String.indexOf. If a match is found, we push the LOCATION of the match onto the 'hits' array. Finally we add the length of our search term to the index and resume searching.

    Also, I swapped to a inline evaluation for the log -- no reason to waste a complex IF when both do the same console logging.

    Hope this helps.
    Java is to JavaScript as Ham is to Hamburger.

  6. #6
    Join Date
    Mar 2009
    Posts
    491
    If the purpose of the exercise is simply to determine the number of times a specific string occurs as a subset of a larger string you can also use the 'split' function of String objects to do this quite easily. Google "javascript String.split" for the precise details. In practice you can have something like:

    Code:
    function timesFound(bigString, sought){
        var arr = bigString.split(sought);
        console.log((arr.length -1) + " instances found");
    }
    Get to know the methods of the common array and string object methods. They are your friends.

  7. #7
    Join Date
    May 2014
    Posts
    3
    Thank you all for these functions! Take in mind I don't know a lot of them (I can count them on my fingers lol), but I'm really happy to learn the ones you suggested me!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles