/*
Perform an escape operation, based on char[], according to the specified type
197661
static void escape(final char[] text, final int offset, final int len, final Writer writer,
                       final UriEscapeType escapeType, final String encoding)
                       throws IOException {

        if (text == null || text.length == 0) {
            return;
        }

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final int codepoint = Character.codePointAt(text, i);

            /*
             * Shortcut: most characters will be alphabetic, and we won't need to do anything at
             * all for them. No need to use the complete UriEscapeType check system at all.
             */
            if (UriEscapeType.isAlpha(codepoint)) {
                continue;
            }

            /*
             * Check whether the character is allowed or not
             */
            if (escapeType.isAllowed(codepoint)) {
                continue;
            }



            /*
             * At this point we know for sure we will need some kind of escape, so we
             * can write all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }

            if (Character.charCount(codepoint) > 1) {
                // This is to compensate that we are actually reading two char[] positions with a single codepoint.
                i++;
            }

            readOffset = i + 1;


            /*
             * -----------------------------------------------------------------------------------------
             *
             * Perform the real escape
             *
             * -----------------------------------------------------------------------------------------
             */

            final byte[] charAsBytes;
            try {
                charAsBytes = new String(Character.toChars(codepoint)).getBytes(encoding);
            } catch (final UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Exception while escaping URI: Bad encoding '" + encoding + "'", e);
            }
            for (final byte b : charAsBytes) {
                writer.write('%');
                writer.write(printHexa(b));
            }


        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: return the original String object if no escape was actually needed. Otherwise
         *                 append the remaining unescaped text to the string builder and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
294456
public function escape($string, $type = 'html', $encoding = 'utf-8') {

		switch($type) {

			case 'url'  : return $this -> escapeUrl($string, $encoding); break;
			case 'css'  : return $this -> escapeCss($string, $encoding); break;
			case 'js'   : return $this -> escapeJs($string, $encoding); break;
			case 'attr' : return $this -> escapeAttr($string, $encoding); break;
			
			default : return $this -> escapeHtml($string, $encoding); break;
		}
	}
928523
def process_escape(self, char):
        ''''''
        # Always only run once, switch back to the last processor.
        self.process_char = self.last_process_char
        if self.part == [] and char in self.whitespace:
            # Special case where \ is by itself and not at the EOL.
            self.parts.append(self.escape_char)
            return
        if char == self.eol_char:
            # Ignore a cr.
            return
        unescaped = self.escape_results.get(char, self.escape_char+char)
        self.part.append(unescaped)
1254885
function() {
        var str = "",
          quote = exprI(index++),
          closed = false,
          ch;

        while (index < length) {
          ch = exprI(index++);
          if (ch === quote) {
            closed = true;
            break;
          } else if (ch === "\\") {
            // Check for all of the common escape codes
            ch = exprI(index++);
            switch (ch) {
              case "n":
                str += "\n";
                break;
              case "r":
                str += "\r";
                break;
              case "t":
                str += "\t";
                break;
              case "b":
                str += "\b";
                break;
              case "f":
                str += "\f";
                break;
              case "v":
                str += "\x0B";
                break;
              default:
                str += "\\" + ch;
            }
          } else {
            str += ch;
          }
        }

        if (!closed) {
          throwError('Unclosed quote after "' + str + '"', index);
        }

        return {
          type: code.LITERAL,
          value: str,
          raw: quote + str + quote
        };
      }
863046
function escapeValue(value) {
        switch (options.type) {
        case 'js':
            return value.replace(/'/g, '\\\'');
        case 'json':
            return value.replace(/"/g, '\\"');
        default:
            return value;
        }
    }
1351793
private static String escape(String string) {
    return StringUtils.escapeString(string, StringUtils.ESCAPE_CHAR, 
                                    charsToEscape);
  }
1312386
static void escape(final char[] text, final int offset, final int len, final Writer writer,
                       final CssIdentifierEscapeType escapeType, final CssIdentifierEscapeLevel escapeLevel)
                       throws IOException {

        if (text == null || text.length == 0) {
            return;
        }

        final int level = escapeLevel.getEscapeLevel();
        final boolean useBackslashEscapes = escapeType.getUseBackslashEscapes();
        final boolean useCompactHexa = escapeType.getUseCompactHexa();

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final int codepoint = Character.codePointAt(text, i);


            /*
             * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at
             * all for them
             */
            if (codepoint <= (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[codepoint] &&
                    (i > offset || codepoint < '0' || codepoint > '9')) {
                // Note how we check whether the first char is a decimal number, in which case we have to escape it
                continue;
            }


            /*
             * Hyphen check: only escape when it's the first char and it's followed by '-' or a digit.
             */
            if (codepoint == '-' && level < 3) {
                if (i > offset || i + 1 >= max) {
                    continue;
                }
                final char c1 = text[i + 1];
                if (c1 != '-' && (c1 < '0' || c1 > '9')) {
                    continue;
                }
            }


            /*
             * Underscore check: only escape when it's the first char.
             */
            if (codepoint == '_' && level < 3 && i > offset) {
                continue;
            }


            /*
             * Shortcut: we might not want to escape non-ASCII chars at all either.
             */
            if (codepoint > (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[ESCAPE_LEVELS_LEN - 1]) {

                if (Character.charCount(codepoint) > 1) {
                    // This is to compensate that we are actually escaping two char[] positions with a single codepoint.
                    i++;
                }

                continue;

            }


            /*
             * At this point we know for sure we will need some kind of escape, so we
             * can write all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }

            if (Character.charCount(codepoint) > 1) {
                // This is to compensate that we are actually reading two char[] positions with a single codepoint.
                i++;
            }

            readOffset = i + 1;


            /*
             * ------------------------------------------------------------------------------------------
             *
             * Perform the real escape, attending the different combinations of BACKSLASH and HEXA escapes
             *
             * ------------------------------------------------------------------------------------------
             */

            if (useBackslashEscapes && codepoint < BACKSLASH_CHARS_LEN) {
                // We will try to use a BACKSLASH ESCAPE

                final char escape = BACKSLASH_CHARS[codepoint];

                if (escape != BACKSLASH_CHARS_NO_ESCAPE) {
                    // Escape found! just write it and go for the next char
                    writer.write(ESCAPE_PREFIX);
                    writer.write(escape);
                    continue;
                }

            }

            /*
             * No escape was possible, so we need hexa escape (compact or 6-digit).
             */

            final char next =
                    ((i + 1 < max) ? text[i + 1] : (char) 0x0);

            if (useCompactHexa) {
                writer.write(ESCAPE_PREFIX);
                writer.write(toCompactHexa(codepoint, next, level));
                continue;
            }

            writer.write(ESCAPE_PREFIX);
            writer.write(toSixDigitHexa(codepoint, next, level));

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: append the remaining unescaped text to the string builder and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
5822
private void escape(String value) {
        int n = value.length();
        int i = 0;
        for (int j = 0; j < n; ++j) {
            int k = ESCAPED_CHARS.indexOf(value.charAt(j));
            if (k >= 0) {
                if (i < j) {
                    append(value, i, j);
                }
                append(ESCAPE_SEQ[k]);
                i = j + 1;
            }
        }
        if (i < n) {
            append(value, i, n);
        }
    }
222992
private static String escape(String input) {
        StringBuilder resultStr = new StringBuilder();
        for (char ch : input.toCharArray()) {
            if (isUnsafe(ch)) {
                resultStr.append('%');
                resultStr.append(toHex(ch / 16));
                resultStr.append(toHex(ch % 16));
            } else {
                resultStr.append(ch);
            }
        }
        return resultStr.toString();
    }
630602
static void escape(final char[] text, final int offset, final int len, final Writer writer,
                       final HtmlEscapeType escapeType, final HtmlEscapeLevel escapeLevel)
                       throws IOException {

        if (text == null || text.length == 0) {
            return;
        }

        final int level = escapeLevel.getEscapeLevel();
        final boolean useHtml5 = escapeType.getUseHtml5();
        final boolean useNCRs = escapeType.getUseNCRs();
        final boolean useHexa = escapeType.getUseHexa();

        final HtmlEscapeSymbols symbols =
                (useHtml5? HtmlEscapeSymbols.HTML5_SYMBOLS : HtmlEscapeSymbols.HTML4_SYMBOLS);

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final char c = text[i];


            /*
             * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at
             * all for them
             */
            if (c <= symbols.MAX_ASCII_CHAR && level < symbols.ESCAPE_LEVELS[c]) {
                continue;
            }


            /*
             * Shortcut: we might not want to escape non-ASCII chars at all either.
             */
            if (c > symbols.MAX_ASCII_CHAR && level < symbols.ESCAPE_LEVELS[symbols.MAX_ASCII_CHAR + 1]) {
                continue;
            }


            /*
             * Compute the codepoint. This will be used instead of the char for the rest of the process.
             */
            final int codepoint = Character.codePointAt(text, i);


            /*
             * At this point we know for sure we will need some kind of escape, so we
             * can write all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }

            if (Character.charCount(codepoint) > 1) {
                // This is to compensate that we are actually escaping two char[] positions with a single codepoint.
                i++;
            }

            readOffset = i + 1;


            /*
             * -----------------------------------------------------------------------------------------
             *
             * Perform the real escape, attending the different combinations of NCR, DCR and HCR needs.
             *
             * -----------------------------------------------------------------------------------------
             */

            if (useNCRs) {
                // We will try to use an NCR

                if (codepoint < symbols.NCRS_BY_CODEPOINT_LEN) {
                    // codepoint < 0x2fff - all HTML4, most HTML5

                    final short ncrIndex = symbols.NCRS_BY_CODEPOINT[codepoint];
                    if (ncrIndex != symbols.NO_NCR) {
                        // There is an NCR for this codepoint!
                        writer.write(symbols.SORTED_NCRS[ncrIndex]);
                        continue;
                    } // else, just let it exit the block and let decimal/hexa escape do its job

                } else if (symbols.NCRS_BY_CODEPOINT_OVERFLOW != null) {
                    // codepoint >= 0x2fff. NCR, if exists, will live at the overflow map (if there is one).

                    final Short ncrIndex = symbols.NCRS_BY_CODEPOINT_OVERFLOW.get(Integer.valueOf(codepoint));
                    if (ncrIndex != null) {
                        writer.write(symbols.SORTED_NCRS[ncrIndex.shortValue()]);
                        continue;
                    } // else, just let it exit the block and let decimal/hexa escape do its job

                }

            }

            /*
             * No NCR-escape was possible (or allowed), so we need decimal/hexa escape.
             */

            if (useHexa) {
                writer.write(REFERENCE_HEXA_PREFIX);
                writer.write(Integer.toHexString(codepoint));
            } else {
                writer.write(REFERENCE_DECIMAL_PREFIX);
                writer.write(String.valueOf(codepoint));
            }
            writer.write(REFERENCE_SUFFIX);

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: append the remaining unescaped text to the writer and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
382497
private static String escapeJavaScriptChars(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '\b':
                    sb.append("\\b");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '"':
                    sb.append("\\\"");
                    break;
                case '\'':
                    sb.append("\\\'");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                default:
                    if (ch < 32 || ch >= 127) {
                        sb.append(String.format("\\u%04X", (int)ch));
                    } else {
                        sb.append(ch);
                    }
                    break;
            }
        }
        return sb.toString();
    }
188582
private void _writeStringCustom(final int len)
			throws IOException, JsonGenerationException
	{
		// And then we'll need to verify need for escaping etc:
		int end = _outputTail + len;
		final int[] escCodes = _outputEscapes;
		final int maxNonEscaped = (_maximumNonEscapedChar < 1) ? 0xFFFF : _maximumNonEscapedChar;
		final int escLimit = Math.min(escCodes.length, maxNonEscaped+1);
		int escCode = 0;
		final CharacterEscapes customEscapes = _characterEscapes;

		output_loop:
		while (_outputTail < end) {
			char c;
			// Fast loop for chars not needing escaping
			escape_loop:
			while (true) {
				c = _outputBuffer[_outputTail];
				if (c < escLimit) {
					escCode = escCodes[c];
					if (escCode != 0) {
						break escape_loop;
					}
				} else if (c > maxNonEscaped) {
					escCode = CharacterEscapes.ESCAPE_STANDARD;
					break escape_loop;
				} else {
					if ((_currentEscape = customEscapes.getEscapeSequence(c)) != null) {
						escCode = CharacterEscapes.ESCAPE_CUSTOM;
						break escape_loop;
					}
				}
				if (++_outputTail >= end) {
					break output_loop;
				}
			}
			int flushLen = (_outputTail - _outputHead);
			if (flushLen > 0) {
				_writer.write(_outputBuffer, _outputHead, flushLen);
			}
			++_outputTail;
			_prependOrWriteCharacterEscape(c, escCode);
		}
	}
824435
public static String escapeXML(final char[] chars, final int offset, final int length) {
        final StringBuilder escaped = new StringBuilder();

        final int end = offset + length;
        for (int i = offset; i < end; ++i) {
            final char c = chars[i];

            switch (c) {
            case '\'':
                escaped.append("&apos;");
                break;
            case '\"':
                escaped.append("&quot;");
                break;
            case '<':
                escaped.append("&lt;");
                break;
            case '>':
                escaped.append("&gt;");
                break;
            case '&':
                escaped.append("&amp;");
                break;
            default:
                escaped.append(c);
            }
        }

        return escaped.toString();
    }
375118
def escape_control_chars!(string)
      string.gsub!(CONTROL_CHARACTERS) do |character|
        UTF8Encoding::REPLACEMENT_SCHEME[character]
      end
      string
    end
409237
static void unescape(final char[] text, final int offset, final int len, final Writer writer,
                         final UriEscapeType escapeType, final String encoding)
                         throws IOException {

        if (text == null) {
            return;
        }

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final char c = text[i];

            /*
             * Check the need for an unescape operation at this point
             */

            if (c != ESCAPE_PREFIX && (c != '+' || !escapeType.canPlusEscapeWhitespace())) {
                continue;
            }


            /*
             * At this point we know for sure we will need some kind of unescape, so we
             * can increase the offset copy all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }


            /*
             * Deal with possible '+'-escaped whitespace (application/x-www-form-urlencoded)
             */
            if (c == '+') {
                // if we reached this point with c == '+', it's escaping a whitespace
                writer.write(' ');
                readOffset = i + 1;
                continue;
            }


            /*
             * ESCAPE PROCESS
             * --------------
             * If there are more than one percent-encoded/escaped sequences together, we will
             * need to unescape them all at once (because they might be bytes --up to 4-- of
             * the same char).
             */

            // Max possible size will be the remaining amount of chars / 3
            final byte[] bytes = new byte[(max-i)/3];
            char aheadC = c;
            int pos = 0;

            while (((i + 2) < max) && aheadC == ESCAPE_PREFIX) {
                bytes[pos++] = parseHexa(text[i + 1], text[i + 2]);
                i += 3;
                if (i < max) {
                    aheadC = text[i];
                }
            }

            if (i < max && aheadC == ESCAPE_PREFIX) {
                // Incomplete escape sequence!
                throw new IllegalArgumentException("Incomplete escaping sequence in input");
            }

            try {
                writer.write(new String(bytes, 0, pos, encoding));
            } catch (final UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Exception while escaping URI: Bad encoding '" + encoding + "'", e);
            }


            readOffset = i;

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: return the original String object if no unescape was actually needed. Otherwise
         *                 append the remaining escaped text and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
198305
static byte[] escapeString(byte b[]) {
        ByteBuffer content = new ByteBuffer();
        escapeString(b, content);
        return content.toByteArray();
    }
811601
function escape(string) {
  return string.replace(/[^]/g, char => {
    const code = char.charCodeAt();

    if (code < 256) return char;

    const escape = code.toString(16);
    const long = escape.length > 2;
    return `\\${long ? 'u' : 'x'}${('0000' + escape).slice(long ? -4 : -2)}`;
  });
}