(string, options)
| 11764 | /*--------------------------------------------------------------------------*/ |
| 11765 | |
| 11766 | var encode = function(string, options) { |
| 11767 | options = merge(options, encode.options); |
| 11768 | var strict = options.strict; |
| 11769 | if (strict && regexInvalidRawCodePoint.test(string)) { |
| 11770 | parseError('forbidden code point'); |
| 11771 | } |
| 11772 | var encodeEverything = options.encodeEverything; |
| 11773 | var useNamedReferences = options.useNamedReferences; |
| 11774 | var allowUnsafeSymbols = options.allowUnsafeSymbols; |
| 11775 | var escapeCodePoint = options.decimal ? decEscape : hexEscape; |
| 11776 | |
| 11777 | var escapeBmpSymbol = function(symbol) { |
| 11778 | return escapeCodePoint(symbol.charCodeAt(0)); |
| 11779 | }; |
| 11780 | |
| 11781 | if (encodeEverything) { |
| 11782 | // Encode ASCII symbols. |
| 11783 | string = string.replace(regexAsciiWhitelist, function(symbol) { |
| 11784 | // Use named references if requested & possible. |
| 11785 | if (useNamedReferences && has(encodeMap, symbol)) { |
| 11786 | return '&' + encodeMap[symbol] + ';'; |
| 11787 | } |
| 11788 | return escapeBmpSymbol(symbol); |
| 11789 | }); |
| 11790 | // Shorten a few escapes that represent two symbols, of which at least one |
| 11791 | // is within the ASCII range. |
| 11792 | if (useNamedReferences) { |
| 11793 | string = string |
| 11794 | .replace(/>\u20D2/g, '>⃒') |
| 11795 | .replace(/<\u20D2/g, '<⃒') |
| 11796 | .replace(/fj/g, 'fj'); |
| 11797 | } |
| 11798 | // Encode non-ASCII symbols. |
| 11799 | if (useNamedReferences) { |
| 11800 | // Encode non-ASCII symbols that can be replaced with a named reference. |
| 11801 | string = string.replace(regexEncodeNonAscii, function(string) { |
| 11802 | // Note: there is no need to check `has(encodeMap, string)` here. |
| 11803 | return '&' + encodeMap[string] + ';'; |
| 11804 | }); |
| 11805 | } |
| 11806 | // Note: any remaining non-ASCII symbols are handled outside of the `if`. |
| 11807 | } else if (useNamedReferences) { |
| 11808 | // Apply named character references. |
| 11809 | // Encode `<>"'&` using named character references. |
| 11810 | if (!allowUnsafeSymbols) { |
| 11811 | string = string.replace(regexEscape, function(string) { |
| 11812 | return '&' + encodeMap[string] + ';'; // no need to check `has()` here |
| 11813 | }); |
| 11814 | } |
| 11815 | // Shorten escapes that represent two symbols, of which at least one is |
| 11816 | // `<>"'&`. |
| 11817 | string = string |
| 11818 | .replace(/>\u20D2/g, '>⃒') |
| 11819 | .replace(/<\u20D2/g, '<⃒'); |
| 11820 | // Encode non-ASCII symbols that can be replaced with a named reference. |
| 11821 | string = string.replace(regexEncodeNonAscii, function(string) { |
| 11822 | // Note: there is no need to check `has(encodeMap, string)` here. |
| 11823 | return '&' + encodeMap[string] + ';'; |
no test coverage detected