Boris Moore's great jsrender library has one bug. I neither fully understand the meaning of $&
(lastMatch) in regex replace groups nor have a idea how to resolve.
This article telling me to not use the function in production environments, and indirectly to not use JsRender
live.
Could anyone explain it to me and give a replacement of the line:
tmplFn(tmplOrMarkup.replace(rEscapeQuotes, "\\$&"), tmpl);
Regards
Unfortunately JsRender and JDK leave the other holding the baby. JsRender says: $% works fine, JDK say never specified and not a bug.
That is not in fact a bug. The MDN article you link to is for the non-standard RegEx.lastMatch()
API, which is a programmatic way of accessing the last match. But JsRender is not using that API.
In fact JsRender is using "$&"
as a replacement pattern in a replacement string, in the someString.replace(regex, replacementstring)
call - which is standard usage in JavaScript RegEx scenarios.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace, where it says:
The replacement string can include the following special replacement patterns: ... $& Inserts the matched substring.
The regex in that line of code is rEscapeQuotes, which is declared as rEscapeQuotes = /['"\\]/g
- and is a valid JavaScript regex.
That line is looking for '
"
or\
and replacing them with the same character preceded by \
.
Incidentally you should not be trying to run the same regex expressions used in JsRender as if they were Java regex expressions, since in Java the rules and validity of regex expressions can be quite different. JsRender of course runs in a JavaScript environment - the browser, or Node.js on the server...