I am having troubles highlighting the test when it finds multiple match.
For exemple : Regex = [ab] || test string = ababab
I don’t understand how it multiplies the outcome or ignore to highlight the other things
I can’t wrap my head around what’s going on.
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(){
let iCheck = caseInsensitiveFlag.checked ? "i" : "";
let gCheck = globalFlag.checked ? "g" : "";
return iCheck+gCheck;
}
function regexFinder(){
let finaly = "";
let flags = getFlags();
let string = stringToTest.textContent
let regexPat = new RegExp(`${regexPattern.value}`, flags)
let finding = string.match(regexPat)
testResult.textContent = finding;
for(let match of finding){
console.log(match);
console.log(finding);
finaly += string.replace(match, `<span class="highlight">${match}</span>`);
}
stringToTest.innerHTML = finaly
}
console.log(caseInsensitiveFlag.value)
testButton.addEventListener("click", () => {
regexFinder();
})
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:148.0) Gecko/20100101 Firefox/148.0
for(let match of finding){
console.log(match);
console.log(finding);
finaly = string.replaceAll(match, `<span class="highlight">${match}</span>`); //Can't find a way where finaly = or +=
}
But i can’t find a way to make it so the final string takes every regex entry into count.
For the (13.) Gu1n34 P1g5 exemple, i can’t find a way to conserve the sentence as it is modified and not replace it with the last for going. How would you suggest me to do so ?
I figured replacing all isn’t the solution and went back to normal replace. Still i can’t find what i need to do.
You can simplify this quite a bit by removing the for loop and instead using a single replace that will satisfy every pattern. Look at .replace with a function as the 2nd parameter, instead of a string. It’s a powerful mechanism to replace things within a string!
There are a couple other little things to fix with your output, but the most important one is fixing the replacement logic. And then once that is fixed, work on the other little things.
Hello, i’ve been trying to document myself about the .replace with a function as a second parameter but i did not find anything that could help me. Instead, i tried using if statement that includes or not “g” flag. I am still confuse on how the replaceAll works. I still don’t understand how I am supposed to do.
I tried a matchAll, even with some next() and Array.from() but I still can’t do anything when there are multiple match without using a for loop. Could you please orient me somewhere helpfull or teach me ?