According to the accepted answer from this question, the following is the syntax for removing the last instance of a certain character from a string (In this case I want to remove the last &):
function remove (string) {
string = string.replace(/&([^&]*)$/, '$1');
return string;
}
console.log(remove("height=74&width=12&"));
But I'm trying to fully understand why it works.
According to regex101.com,
/&([^&]*)$/
&matches the character & literally (case sensitive)1st Capturing Group
([^&]*)Match a single character not present in the list below[^&]*
*Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
&matches the character & literally (case sensitive)
$asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
So if we're matching the character & literally with the first &:
Then why are we also "matching a single character not present in the following list"?
Seems counter productive.
And then, "$ asserts position at the end of the string" - what does this mean? That it starts searching for matches from the back of the string first?
And finally, what is the $1 doing in the replaceValue? Why is it $1 instead of an empty string? ""


&, then match and capture what follows that&, until the end of the pattern. The way the pattern is written, the&must be the last one in the input. Then, it replaces everything with just the capture group, effectively deleting the last&."height=74&width=12&"- it matches the first&, and then matches and captures all of this:width=12&? And then it removes the&from that capture group, since&is what's declared outside of the capture group, initially?&would be removed, see the demo.([^&]*)captures all characters except for&? Why is only the final&removed?