CyberChef/src/js/operations/Unicode.js

67 lines
1.2 KiB
JavaScript
Raw Normal View History

import Utils from '../core/Utils';
2016-11-28 10:42:58 +00:00
/**
* Unicode operations.
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*
* @namespace
*/
2016-11-29 00:22:34 +00:00
const Unicode = {
2016-11-28 10:42:58 +00:00
/**
* @constant
* @default
*/
2016-11-29 00:22:34 +00:00
PREFIXES: ['\\u', '%u', 'U+'],
2016-11-28 10:42:58 +00:00
/**
* Unescape Unicode Characters operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
2016-11-29 00:22:34 +00:00
run_unescape(input, args) {
let prefix = Unicode._prefix_to_regex[args[0]],
regex = new RegExp(`${prefix}([a-f\\d]{4,6})`, 'ig'),
output = '',
m,
i = 0;
while (m = regex.exec(input)) {
2016-11-28 10:42:58 +00:00
// Add up to match
2016-11-29 00:22:34 +00:00
output += input.slice(i, m.index);
i = m.index;
2016-11-28 10:42:58 +00:00
// Add match
2016-11-29 00:22:34 +00:00
output += Utils.chr(parseInt(m[1], 16));
i = regex.lastIndex;
}
2016-11-28 10:42:58 +00:00
// Add all after final match
2016-11-29 00:22:34 +00:00
output += input.slice(i, input.length);
return output;
},
2016-11-28 10:42:58 +00:00
/**
* Lookup table to add prefixes to unicode delimiters so that they can be used in a regex.
*
* @private
* @constant
*/
2016-11-29 00:22:34 +00:00
_prefix_to_regex: {
'\\u': '\\\\u',
'%u': '%u',
'U+': 'U\\+',
},
2016-11-28 10:42:58 +00:00
};
export default Unicode;