diff --git a/src/serialization/sb2.js b/src/serialization/sb2.js index e925929f..e606f5a6 100644 --- a/src/serialization/sb2.js +++ b/src/serialization/sb2.js @@ -199,7 +199,7 @@ const parseScripts = function (scripts, blocks, addBroadcastMsg, getVariableId, */ const generateVariableIdGetter = (function () { let globalVariableNameMap = {}; - const namer = (targetId, name, type) => `${targetId}-${name}-${type}`; + const namer = (targetId, name, type) => `${targetId}-${StringUtil.replaceUnsafeChars(name)}-${type}`; return function (targetId, topLevel) { // Reset the global variable map if topLevel if (topLevel) globalVariableNameMap = {}; diff --git a/src/util/string-util.js b/src/util/string-util.js index c308cc6c..7614eff7 100644 --- a/src/util/string-util.js +++ b/src/util/string-util.js @@ -57,6 +57,25 @@ class StringUtil { return value; }); } + /** + * A function to replace unsafe characters (not allowed in XML) with safe ones. This is used + * in cases where we're replacing non-user facing strings (e.g. variable IDs). + * When replacing user facing strings, the xmlEscpe utility function should be used + * instead so that the user facing string does not change how it displays. + * @param {!string} unsafe Unsafe string possibly containing unicode control characters. + * @return {string} String with control characters replaced. + */ + static replaceUnsafeChars (unsafe) { + return unsafe.replace(/[<>&'"]/g, c => { + switch (c) { + case '<': return 'lt'; + case '>': return 'gt'; + case '&': return 'amp'; + case '\'': return 'apos'; + case '"': return 'quot'; + } + }); + } } module.exports = StringUtil;