Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11

Thread: Match function

  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    23
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Match function

    Code:
    
    function displayMessage(text) {
    
    	// Open a new window 
    var msgWindow = window.open('', 'Message');
     
      // Write message in the new Window 
      msgWindow.document.write(text);
    
      // Raise this window, in case it's not visible
      msgWindow.focus();
      
    }
    
    //Enter total number of questions:
    var totalquestions=30
    var mcquestions=13
    var saquestions=18
    
    var correctchoices=new Array("a","a","b","c","b","c","a","a","b","c","a","b","b");
    
    var correctanswers=new Array("memory locations","_ underscore","x=5+5;","20","Else","lose win","ticker = ticker + 1;","Ticker = ticker + 1;","300.000","Jonathon \b","var","var counter;","var mark = 50, 70");
    
    var shortanswers=new Array(/identifier/gi,/assignment/i,/false/i,/true/i,/false/i,/reverse of the boolean result/i,/the variable will be once the line is executed/i,/var/i,/value/i,/2/i,/4/i,/2/i,/3/i,/no semi colon/i,/no spacebetween else and if/i,/missing curly bracket/i,/need else instead of else if/i);
    
    function gradeit(){
    var actualchoices=new Array()
    var msg1=new Array()
    var msg2=new Array()
    var correctanswersno=0
    var t=0
    var f=0
    var sa=0
    
    var foundMatches = 0;
    var displaymcanswers=""
    var displaysaanswers=""
    	
    
    
    //Works out mark for Short-answer Questions//
    
    for (s=1;s<saquestions;s++){
    var saanswers = []
       if ((saanswers.push(((document.Questionform["sa" +  s]).value).match(shortanswers[s-1]))) == 1 ) {
    	  msg2[f]=s+")"+" Correct";
    	  sa++;
       } else {
       msg2[f]=s+")"+" Incorrect: <br>Correct answer should include the word: "+shortanswers[s-1];  
    	}
    	f = f + 1;
    }
    This piece of code marks answers from a user which they have entered into textboxes. So for each answer the code uses the match function to see if it matches a specific pattern. However, at the moment the code says all the user answers are correct when are answers are actually wrong. Ideas?

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Look again at your code. (After pulling out the unneeded parentheses):

    Code:
    if (
            saanswers.push(
                 document.Questionform["sa" +  s].value.match(shortanswers[s-1])
            )
            == 1 
    ) {
    or with all your parens still in place, though it's harder to see:
    Code:
    if (
          (
              saanswers.push(
                  (
                      (
                          document.Questionform["sa" +  s]
                      ).value
                  ).match(shortanswers[s-1])
             )
         ) == 1 
    ) {
    You are comparing the result of the .push( ) method with 1!!!! You aren't gettting the result of the match() method, at all.

    And the result of the push() is the new number of elements in the array that was pushed to!!!

    *********

    But even if you thought you were comparing the result of the .match(), why would you ever expect it to return a value of 1?? It returns null if no match and an *array* if there is a mach.

    *********

    Try this:
    Code:
        var q = document.Questionform["sa" +  s].value.match(shortanswers[s-1]);
        saanswers.push(q);
        if ( q != null ) {
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    bradz1993 (03-21-2012)

  • #3
    New Coder
    Join Date
    Oct 2011
    Posts
    23
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Seems to work thanks. Also how do I do a pattern so that its searches for two words e.g. if the user enters one word or the other they get it correct

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Code:
    /(zamboni|rowrbazzle|cinderella)/i
    Or get fancier:
    Code:
    /(danc(e|ing)|tarr(y|ied\ing))/i
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    Oct 2011
    Posts
    23
    Thanks
    4
    Thanked 0 Times in 0 Posts
    What does the second statement (fancier one) do?

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,986
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by bradz1993 View Post
    What does the second statement (fancier one) do?
    Nothing! Syntax error!

    var str = "dancing".match(/danc(e|ing)/)
    alert (str); // returns dancing,ing (both matched).

    Correct code examples:-

    Code:
    var str="Old Pedant is at a dance, dancing, but he will not marry or tarry with Harry or Larry, nor has he ever tarried with Harry, nor will he be found to be tarrying"; 
    var pattern=/dance|dancing|\btarry\b|tarried|tarrying/gi;
    alert(str.match(pattern));
    var pattern = /\bdanc\w+|\b[a-z]+arr\w+/gi;
    alert(str.match(pattern));
    var pattern = /\bdanc\w+|\b[a-gj-z]+arr\w+/gi;
    alert(str.match(pattern));
    var pattern = /\b(tarr[iy](\w+))/gi;
    alert(str.match(pattern));
    var pattern = /\b(tarr[iy](\w+)?)/gi;
    alert(str.match(pattern));
    Last edited by Philip M; 03-21-2012 at 11:59 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Ah, see, Philip, I wouldn't use match(), at all, to satisfy the requirements of his request. I see no reason. I'd just use test() on the regexp.

    But in any case, why do you say "syntax error". If it was really a syntax error it wouldn't have compiled, much less run.

    And your example:
    var str = "dancing".match(/danc(e|ing)/)
    alert (str); // returns dancing,ing (both matched).
    is doing the *RIGHT* thing. The match function is *supposed* to return an ARRAY of all matches. You mislead people by naming the variable that holds the result of the match as str. A better name would be arrMatches, perhaps.

    Anyway, if you ONLY check to see if match is null/non-null then the code works.

    For example, try this:
    var str = "ing".match(/danc(e|ing)/)
    alert (str);
    alert("match returned null? " + (str == null) );
    Last edited by Old Pedant; 03-21-2012 at 07:28 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    This is so bizarre. I gave a nice long reply about how the "fancier" code worked last night, and it is not here today!

    To make a long story short, my code allows you to supply multiple endings to a word.

    How about a demo?
    Code:
    <script type="text/javascript">
    var re = /(danc(e|ing)|tarr(y|ied|ying))/i
    
    function testAnswer( ans )
    {
        document.write("The answer '" + ans + "' " 
                        + ( re.test(ans) ? "is valid" : "is wrong" ) 
                        + "<hr/>\n");
    }
    
    testAnswer("zambonis rule");
    testAnswer("we went dancing at night");
    testAnswer("we danced all night");
    testAnswer("he who tarries is lost");
    testAnswer("don't tarry too long");
    testAnswer("tarred and feathered");
    testAnswer("daunting and ferrying"); // an notice I do *NOT* get false-positive from this
    </script>
    Go on, try it.

    But, yes, you *CAN* use match() if you *ONLY* check for null vs. non-null. Thus:

    Code:
    <script type="text/javascript">
    var re = /(danc(e|ing)|tarr(y|ied|ying))/i
    
    function testAnswer( ans )
    {
        document.write("The answer '" + ans + "' " 
                        + ( ans.match(re) != null ? "is valid" : "is wrong" ) 
                        + "<hr/>\n");
    }
    
    testAnswer("zambonis rule");
    testAnswer("we went dancing at night");
    testAnswer("we danced all night");
    testAnswer("he who tarries is lost");
    testAnswer("don't tarry too long");
    testAnswer("tarred and feathered");
    testAnswer("daunting and ferrying"); // an notice I do *NOT* get false-positive from this
    </script>
    Try that, as well.

    You just can't use the form that I did with match to get an array that makes sense. Because, as Philip showed, you get *ALL* the matches, AS AN ARRAY.
    Last edited by Old Pedant; 03-21-2012 at 07:30 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,986
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by Old Pedant View Post
    But in any case, why do you say "syntax error". If it was really a syntax error it wouldn't have compiled, much less run.
    /(danc(e|ing)|tarr(y|ied\ing))/i


    Actually not a syntax error. The \ is an escape character, which here does nothing. The regex is in fact the equivalent of

    /(danc(e|ing)|tarr(y|ieding))/i

    which would match tarry or tarrieding.

    I agree that test() is better, but the thread heading is match function, and he says "the code uses the match function". That would seem to me to be a reason for demonstrating match().
    Last edited by Philip M; 03-21-2012 at 07:56 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Here's some example code that explores all that match does:
    Code:
    <script type="text/javascript">
    var matches = "dancing".match(/danc(e|ing)/)
    document.write("Matches is an array with added properties and " + matches.length + " elements<hr>");
    document.write("Properties of matches:<ul>"
          + "<li>input: " + matches.input + "</li>"
          + "<li>index: " + matches.index + "</li>"
          + "<li>lastIndex: " + matches.lastIndex + "</li></ul><hr/>");
    
    for ( var i = 0; i < matches.length; ++i )
    {
        var m = matches[i];
        document.write("match #" + i + " is " + m + "<br/>");
    }
    </script>
    With FF and Chrome, lastIndex is undefined. MSIE defines it.

    Try other regular expression and strings to see how you can utilize all that.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Oh, I thought you meant the "danc(e|ing)" part had a syntax error. Yeah, the \ was a typo. But, then, I also left out the y. See above posts.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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