Merge Vel0z/string_escaping_unescaping

Updated to new project format
This commit is contained in:
Matt C 2017-08-04 11:50:45 +01:00
commit 3186335f47
3 changed files with 80 additions and 0 deletions

View File

@ -188,6 +188,8 @@ const Categories = [
"Parse UNIX file permissions",
"Swap endianness",
"Parse colour code",
"Escape String",
"Unescape String",
]
},
{

View File

@ -3252,6 +3252,20 @@ const OperationConfig = {
}
]
},
"Escape String": {
description: "Escapes a string so that it can be embedded in another. For example, <code>Don't stop me now</code> becomes <code>Don\\'t stop me now</code>.",
run: StrUtils.run_escape,
inputType: "string",
outputType: "string",
args: []
},
"Unescape String": {
description: "Unescapes a string that was embedded inside another so that it can be used in it's own right. For example, <code>Don\\'t stop me now</code> becomes <code>Don't stop me now</code>.",
run: StrUtils.run_unescape,
inputType: "string",
outputType: "string",
args: []
},
"To Morse Code": {
description: "Translates alphanumeric characters into International Morse Code.<br><br>Ignores non-Morse characters.<br><br>e.g. <code>SOS</code> becomes <code>... --- ...</code>",
run: MorseCode.runTo,

View File

@ -460,6 +460,70 @@ const StrUtils = {
return Utils.parseEscapedChars(input);
},
/**
* @constant
* @default
*/
ESCAPE_REPLACEMENTS: [
{"escaped": "\\\\", "unescaped": "\\"}, // Must be first
{"escaped": "\\'", "unescaped": "'"},
{"escaped": "\\\"", "unescaped": "\""},
{"escaped": "\\n", "unescaped": "\n"},
{"escaped": "\\r", "unescaped": "\r"},
],
/**
* Escapes a string for embedding in another string.
*
* Example: "Don't do that" -> "Don\'t do that"
*
* @author Vel0x [dalemy@microsoft.com]
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
runEscape: function(input, args) {
return StrUtils._replace_by_keys(input, "unescaped", "escaped");
},
/**
* Unescapes a string that was part of another string
*
* Example: "Don\'t do that" -> "Don't do that"
*
* @author Vel0x [dalemy@microsoft.com]
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
runUnescape: function(input, args) {
return StrUtils._replace_by_keys(input, "escaped", "unescaped");
},
/**
* Replaces all matching tokens in ESCAPE_REPLACEMENTS with the correction. The
* ordering is determined by the pattern_key and the replacement_key.
*
* @author Vel0x [dalemy@microsoft.com]
* @author Matt C [matt@artemisbot.uk]
*
* @param {string} input
* @param {string} pattern_key
* @param {string} replacement_key
* @returns {string}
*/
_replaceByKeys: function(input, patternKey, replacementKey) {
const replacementsLength = StrUtils.ESCAPE_REPLACEMENTS.length;
let output = input;
for (let i = 0; i < replacementsLength; i++) {
const replacement = StrUtils.ESCAPE_REPLACEMENTS[i];
output = output.split(replacement[patternKey]).join(replacement[replacementKey]);
}
return output;
},
/**
* Head lines operation.