Skip to content

Commit

Permalink
Fix use of asterisk in regular expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
otacke committed Mar 18, 2021
1 parent 8b6a3af commit 668a847
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions scripts/essay.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,14 +439,26 @@ H5P.Essay = function ($, Question) {
return that.htmlDecode(alternative);
});

/*
* Get all matches to regular expressions and pretend the matches were
* given as alternative answers in order to be able to detect them.
* This result computation might need a rewrite ...
*/
const regularExpressionMatches = that
.getRegExpAlternatives(alternatives, that.getInput(), caseSensitive)
.map(function (match) {
// Allow to differentiate from wildcard asterisk
return match = match.replace(/\*/, Essay.REGULAR_EXPRESSION_ASTERISK);
});

// Not chained, because we still need the old value inside
alternatives = alternatives
// only "normal" alternatives
.filter(function (alternative) {
return (alternative[0] !== '/' || alternative[alternative.length - 1] !== '/');
})
// regular matches found in text for alternatives
.concat(that.getRegExpAlternatives(alternatives, that.getInput(), caseSensitive))
.concat(regularExpressionMatches)
// regular matches could match empty string
.filter(function (alternative) {
return alternative !== '';
Expand Down Expand Up @@ -645,7 +657,10 @@ H5P.Essay = function ($, Question) {
let pos = -1;
let front = 0;

needle = needle.replace(/\*/, '');
needle = needle
.replace(/\*/, '') // Wildcards checked separately
.replace(new RegExp(Essay.REGULAR_EXPRESSION_ASTERISK, 'g'), '*'); // Asterisk from regexp

while ((pos = haystack.indexOf(needle)) !== -1) {
if (H5P.TextUtilities.isIsolated(needle, haystack)) {
result.push({'keyword': needle, 'match': needle, 'index': front + pos});
Expand Down Expand Up @@ -906,5 +921,8 @@ H5P.Essay = function ($, Question) {
/** @constant {string} */
Essay.DEFAULT_DESCRIPTION = 'Essay';

/** @constant {string} */
Essay.REGULAR_EXPRESSION_ASTERISK = ':::H5P-Essay-REGEXP-ASTERISK:::';

return Essay;
}(H5P.jQuery, H5P.Question);

0 comments on commit 668a847

Please sign in to comment.