MCPcopy Create free account
hub / github.com/zxlie/FeHelper / encode

Function encode

apps/en-decode/he.js:140–216  ·  view source on GitHub ↗
(string, options)

Source from the content-addressed store, hash-verified

138 /*--------------------------------------------------------------------------*/
139
140 var encode = function(string, options) {
141 options = merge(options, encode.options);
142 var strict = options.strict;
143 if (strict && regexInvalidRawCodePoint.test(string)) {
144 parseError('forbidden code point');
145 }
146 var encodeEverything = options.encodeEverything;
147 var useNamedReferences = options.useNamedReferences;
148 var allowUnsafeSymbols = options.allowUnsafeSymbols;
149 var escapeCodePoint = options.decimal ? decEscape : hexEscape;
150
151 var escapeBmpSymbol = function(symbol) {
152 return escapeCodePoint(symbol.charCodeAt(0));
153 };
154
155 if (encodeEverything) {
156 // Encode ASCII symbols.
157 string = string.replace(regexAsciiWhitelist, function(symbol) {
158 // Use named references if requested & possible.
159 if (useNamedReferences && has(encodeMap, symbol)) {
160 return '&' + encodeMap[symbol] + ';';
161 }
162 return escapeBmpSymbol(symbol);
163 });
164 // Shorten a few escapes that represent two symbols, of which at least one
165 // is within the ASCII range.
166 if (useNamedReferences) {
167 string = string
168 .replace(/>\u20D2/g, '>⃒')
169 .replace(/<\u20D2/g, '<⃒')
170 .replace(/fj/g, 'fj');
171 }
172 // Encode non-ASCII symbols.
173 if (useNamedReferences) {
174 // Encode non-ASCII symbols that can be replaced with a named reference.
175 string = string.replace(regexEncodeNonAscii, function(string) {
176 // Note: there is no need to check `has(encodeMap, string)` here.
177 return '&' + encodeMap[string] + ';';
178 });
179 }
180 // Note: any remaining non-ASCII symbols are handled outside of the `if`.
181 } else if (useNamedReferences) {
182 // Apply named character references.
183 // Encode `<>"'&` using named character references.
184 if (!allowUnsafeSymbols) {
185 string = string.replace(regexEscape, function(string) {
186 return '&' + encodeMap[string] + ';'; // no need to check `has()` here
187 });
188 }
189 // Shorten escapes that represent two symbols, of which at least one is
190 // `<>"'&`.
191 string = string
192 .replace(/&gt;\u20D2/g, '&nvgt;')
193 .replace(/&lt;\u20D2/g, '&nvlt;');
194 // Encode non-ASCII symbols that can be replaced with a named reference.
195 string = string.replace(regexEncodeNonAscii, function(string) {
196 // Note: there is no need to check `has(encodeMap, string)` here.
197 return '&' + encodeMap[string] + ';';

Callers

nothing calls this directly

Calls 4

parseErrorFunction · 0.85
hasFunction · 0.85
escapeBmpSymbolFunction · 0.85
mergeFunction · 0.70

Tested by

no test coverage detected