From 5a22c9c59b62051c38e94bdfabfe38d28e3e740c Mon Sep 17 00:00:00 2001 From: Jeff Parsons Date: Fri, 23 Jun 2017 10:03:27 -0700 Subject: [PATCH] Added more documentation regarding a REALLY annoying feature of JavaScript's string replace() method --- modules/pcx86/lib/keyboard.js | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/modules/pcx86/lib/keyboard.js b/modules/pcx86/lib/keyboard.js index 20a41b0aa..792a46ba5 100644 --- a/modules/pcx86/lib/keyboard.js +++ b/modules/pcx86/lib/keyboard.js @@ -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;