+ 1
Read description
So I was trying to make this code display whatever you typed and then highlight the E's(was experimenting with Regular Expressions) I ran into a little problem var C = p.innerHTML.replace(/e/gi, "<span>e</span>"); as you can see, this would replace all E's with lowercase e's. The solution I was given confused me. var C = p.innerHTML.replace(/(e)/gi, "<span>$1</span>"); Why is the e surrounded by parentheses and what exactly does $1 do? https://code.sololearn.com/W5AR7NmwcPNV/?ref=app (this is the code I was referring to)
1 Respuesta
+ 4
Daniel Cooper, that's capturing groups.
the match inside the parentheses is remembered and assigned a number.
$1, $2 , $3 and so on. Depending on the number of groups.
You can use those numbers like variables for the replacement.
Here's another explanation:
https://flaviocopes.com/javascript-regular-expressions/#capturing-groups