...

View Full Version : Match function



bradz1993
03-20-2012, 11:15 PM
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?

Old Pedant
03-20-2012, 11:52 PM
Look again at your code. (After pulling out the unneeded parentheses):



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:


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:


var q = document.Questionform["sa" + s].value.match(shortanswers[s-1]);
saanswers.push(q);
if ( q != null ) {

bradz1993
03-21-2012, 12:00 AM
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

Old Pedant
03-21-2012, 12:05 AM
/(zamboni|rowrbazzle|cinderella)/i


Or get fancier:


/(danc(e|ing)|tarr(y|ied\ing))/i

bradz1993
03-21-2012, 12:18 AM
What does the second statement (fancier one) do?

Philip M
03-21-2012, 09:11 AM
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:-


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));

Old Pedant
03-21-2012, 07:18 PM
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) );

Old Pedant
03-21-2012, 07:28 PM
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?


<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:



<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.

Philip M
03-21-2012, 07:48 PM
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().

Old Pedant
03-21-2012, 07:50 PM
Here's some example code that explores all that match does:


<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.

Old Pedant
03-21-2012, 07:51 PM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum