Added more documentation regarding a REALLY annoying feature of JavaScript's string replace() method

This commit is contained in:
Jeff Parsons 2017-06-23 10:03:27 -07:00 committed by Jeff Parsons
commit 5a22c9c59b

View file

@ -411,15 +411,23 @@ class Keyboard extends Component {
*
* If you want any of those sequences to be typed as-is, then you must specify two "$" (ie, "$$").
*
* WARNING: the JavaScript replace() function ALWAYS interprets "$" specially in replacement strings, even when
* the search string is NOT a RegExp, and since we build machine definitions on a page from a potentially
* indeterminate number of string replace() operations, multiple dollar signs could eventually get reduced to a
* single dollar sign BEFORE we get here.
* WARNING: the JavaScript replace() function ALWAYS interprets "$" specially in replacement strings,
* even when the search string is NOT a RegExp; specifically:
*
* To compensate, I've attempted add 'replace(/\$/g, "$$$$")' operations where currently needed; eg, in the
* $$ Inserts a "$"
* $& Inserts the matched substring
* $` Inserts the portion of the string that precedes the matched substring
* $' Inserts the portion of the string that follows the matched substring
* $n Where n is a positive integer less than 100, inserts the nth parenthesized sub-match string,
* provided the first argument was a RegExp object
*
* Since we build machine definitions on a page from a potentially indeterminate number of string replace()
* operations, multiple dollar signs could eventually get reduced to a single dollar sign BEFORE we get here.
*
* To compensate, I've attempted add replace(/\$/g, "$$$$") operations where currently needed; eg, in the
* markout.js convertMDMachineLinks() function, the htmlout.js addFilesToHTML() function, and the embed.js
* parseXML() function. Unfortunately, this is something that will be extremely difficult to prevent from breaking
* down the road. So, heads up to future me....
* parseXML() function. Unfortunately, this is something that will be extremely difficult to prevent from
* breaking down the road. So, heads up to future me....
*
* @this {Keyboard}
* @param {string|undefined} sKeys
@ -444,6 +452,11 @@ class Keyboard extends Component {
}
sKeys = sKeys.replace('$' + match[1], sReplace);
}
/*
* Any lingering "$$" sequences are now converted to "$"; as discussed above, replace() interprets any
* "$$" in the replacement string as "$", so to the casual observer, it might not look like we're downsizing
* the dollar signs, but we actually are.
*/
sKeys = sKeys.replace(/\$\$/g, "$$");
}
return sKeys;