File size: 1,513 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
/**
* Encode single characters with backslashes.
* @param {string} charStr single-character string.
* @returns {string} backslash escaped character.
* @copyright (c) 2013, GoInstant Inc., a salesforce.com company.
* @license BSD-3-Clause
* @see https://github.com/goinstant/secure-filters/blob/HEAD/lib/secure-filters.js
* @private
*/
function jsSlashEncoder( charStr ) {
const code = charStr.charCodeAt( 0 );
const hex = code.toString( 16 ).toUpperCase();
if ( code < 0x80 ) {
// ASCII
if ( hex.length === 1 ) {
return '\\x0' + hex;
}
return '\\x' + hex;
}
// Unicode
switch ( hex.length ) {
case 2:
return '\\u00' + hex;
case 3:
return '\\u0' + hex;
case 4:
return '\\u' + hex;
default:
// charCodeAt() JS shouldn't return code > 0xFFFF, and only four hex
// digits can be encoded via `\u`-encoding, so return REPLACEMENT
// CHARACTER U+FFFD.
return '\\uFFFD';
}
}
/**
* Create JSON serialized string suitable for inclusion in HTML
* @param {any} value The variable to be serialized
* @returns {string} JSON serialized string
*/
exports.jsonStringifyForHtml = function ( value ) {
const jsonInHtmlFilter = /[^\x22,\-.0-9:A-Z[\x5C\]_a-z{}]/g;
const cdataClose = /\]\](?:>|\\x3E|\\u003E)/gi;
return (
JSON.stringify( value )
.replace( jsonInHtmlFilter, jsSlashEncoder )
// prevent breaking out of CDATA context. Escaping < below is sufficient
// to prevent opening a CDATA context.
.replace( cdataClose, '\\x5D\\x5D\\x3E' )
);
};
|