Tell us what’s happening:
problem with step 18 “When the inner HTML of stringToTest is Gu1n34 P1g5, the value of regexPattern is \d+, and the global flag is checked, the inner text of #result should become 1, 34, 1, 5 by clicking the testButton button”.
The list returned by matchAll on line 33 does not contain the first matching element (1 in case of Gu1n34 P1g5). I don’t understand where the logical error lies, as all matching elements should be returned.
Your code so far
<!-- file: index.html -->
/* file: styles.css */
/* file: script.js */
const regexPattern = document.getElementById("pattern");
const stringToTest = document.getElementById("test-string");
const testButton = document.getElementById("test-btn");
const testResult = document.getElementById("result");
const caseInsensitiveFlag = document.getElementById("i");
const globalFlag = document.getElementById("g");
function getFlags() {
const iFlag = caseInsensitiveFlag.checked ? "i" : "";
const gFlag = globalFlag.checked ? "g" : "";
return `${iFlag}${gFlag}`;
}
function highlightText(regex) {
stringToTest.innerHTML = stringToTest.textContent; // Remove all <span> elements
stringToTest.innerHTML = stringToTest.innerHTML.replace(
regex,
"<span class=\"highlight\">$&</span>");
}
function showResult(regex) {
if (!regex.test(stringToTest.textContent)) {
testResult.textContent = "no match";
return;
};
if (!regex.global) {
testResult.textContent = stringToTest.textContent.match(regex)[0];
} else {
testResult.textContent =
Array.from(stringToTest.textContent.matchAll(regex))
.map(match => { return `${match[0]}, `}).join("");
// Does not include the first element (1 in case of Gu1n34 P1g5)
}
}
testButton.addEventListener("click", () => {
const regex = RegExp(regexPattern.value, getFlags());
highlightText(regex);
showResult(regex);
});
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0
Challenge Information:
Build a RegEx Sandbox - Build a RegEx Sandbox