Encodes a character to a backslash code (if not ASCII)
357356
public static String encodeBackslashToASCII(char c) {
    if (c >= 32 && c < 128 && c != '\\' && c != '"') return ("" + c);
    String hex = Integer.toHexString(c);
    while (hex.length() < 4)
      hex = "0" + hex;
    return ("\\u" + hex);
  }
935457
def shell_escape(s):
    
    """
    if isinstance(s, PosixPath):
        s = unicode_(s)
    elif isinstance(s, bytes):
        s = s.decode('utf-8')
    if not s or any(c not in safe_shell_chars for c in s):
        return '"%s"' % (s.replace('\\', '\\\\')
                          .replace('"', '\\"')
                          .replace('`', '\\`')
                          .replace('$', '\\$'))
    else:
        return s
649212
def escape_unicode_string(u):
    
    def replacer(matchobj):
        if ord(matchobj.group(1)) == 127:
            return "\\x7f"
        if ord(matchobj.group(1)) == 92: # backslash
            return "\\\\"
        return REPLACEMENT_TABLE[ord(matchobj.group(1))]
    return re.sub("([\\000-\\037\\134\\177])", replacer, u)
270773
private static String escapeSpecialAsciiAndNonAscii(String path) {
    int len = path.length(), ch;
    StringBuilder buffer = new StringBuilder(len * 3);
    // change C:/blah to /C:/blah
    if (len >= 2 && path.charAt(1) == ':') {
      ch = Character.toUpperCase(path.charAt(0));
      if (ch >= 'A' && ch <= 'Z') {
        buffer.append('/');
      }
    }
    // for each character in the path
    int i = 0;
    for (i = 0; i < len; i++) {
      ch = path.charAt(i);
      // if it's not an ASCII character, break here, and use UTF-8 encoding
      if (ch >= 128) {
        break;
      }
      if (gNeedEscaping[ch]) {
        buffer.append('%');
        buffer.append(gAfterEscaping1[ch]);
        buffer.append(gAfterEscaping2[ch]);
      } else {
        buffer.append((char) ch);
      }
    }
    // we saw some non-ascii character
    if (i < len) {
      // get UTF-8 bytes for the remaining sub-string
      byte[] bytes = null;
      byte b;
      bytes = path.substring(i).getBytes(StandardCharsets.UTF_8);
      len = bytes.length;
      // for each byte
      for (i = 0; i < len; i++) {
        b = bytes[i];
        // for non-ascii character: make it positive, then escape
        if (b < 0) {
          ch = b + 256;
          buffer.append('%');
          buffer.append(gHexChs[ch >> 4]);
          buffer.append(gHexChs[ch & 0xf]);
        } else if (gNeedEscaping[b]) {
          buffer.append('%');
          buffer.append(gAfterEscaping1[b]);
          buffer.append(gAfterEscaping2[b]);
        } else {
          buffer.append((char) b);
        }
      }
    }
    return buffer.toString();
  }
976881
function(string) {
            // If the string contains no control characters, no quote characters, and no
            // backslash characters, then we can simply slap some quotes around it.
            // Otherwise we must also replace the offending characters with safe
            // sequences.    
            var m = {
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };
            if(/["\\\x00-\x1f]/.test(string)) {
                return '"' + string.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if(c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + string + '"';
        }
1250388
function encodeSpecialCharacters (str) {
  return encodeURI(str).replace(/[!'()* ]/g, function (char) {
    return '%' + char.charCodeAt(0).toString(16)
  })
}
663926
def _escape_sequence(self, char):
        

        num = ord(char)
        if char == "[":
            self.state = "escape-lb"
        elif char == "(":
            self.state = "charset-g0"
        elif char == ")":
            self.state = "charset-g1"
        elif num in self.escape:
            self.dispatch(self.escape[num])
            self.state = "stream"
        elif self.fail_on_unknown_esc:
            raise StreamProcessError("Unexpected character '%c' == '0x%02x'" % (char, ord(char)))
625106
function _convertUnicode(originalStr) {
  let m;
  let c;
  let cStr;
  let lastI = 0;

  // Matches \u#### but not \\u####
  const unicodeRegex = /\\u[0-9a-fA-F]{4}/g;

  let convertedStr = '';
  while ((m = unicodeRegex.exec(originalStr))) {
    // Don't convert if the backslash itself is escaped
    if (originalStr[m.index - 1] === '\\') {
      continue;
    }

    try {
      cStr = m[0].slice(2); // Trim off start
      c = String.fromCharCode(parseInt(cStr, 16));
      if (c === '"') {
        // Escape it if it's double quotes
        c = `\\${c}`;
      }

      // + 1 to account for first matched (non-backslash) character
      convertedStr += originalStr.slice(lastI, m.index) + c;
      lastI = m.index + m[0].length;
    } catch (err) {
      // Some reason we couldn't convert a char. Should never actually happen
      console.warn('Failed to convert unicode char', m[0], err);
    }
  }

  // Finally, add the rest of the string to the end.
  convertedStr += originalStr.slice(lastI, originalStr.length);

  return convertedStr;
}
500309
private String escapeAttributeNameSpecialCharacters(String str)
    {
        if (str != null)
        {
            StringBuffer strBuf = new StringBuffer("");

            for (int i = 0; i < str.length(); i++)
            {
                char strChar = str.charAt(i);

                switch (strChar)
                {
                    case ':':
                        {
                            strBuf.append("_ns-sep_");
                            break;
                        }
                    default:
                        {
                            strBuf.append(strChar);
                            break;
                        }
                }
            }
            str = strBuf.toString();
        }
        return str;
    }
931535
public static String encode(String str) {
    if (str == null) {
      return "";
    }

    return ESCAPER.escape(str)
      .replaceAll("\\!", "%21")
      .replaceAll("\\$", "%24")
      .replaceAll("\\&", "%26")
      .replaceAll("\\'", "%27")
      .replaceAll("\\(", "%28")
      .replaceAll("\\)", "%29")
      .replaceAll("\\*", "%2A")
      .replaceAll("\\+", "%2B")
      .replaceAll("\\,", "%2C")
      .replaceAll("\\/", "%2F")
      .replaceAll("\\:", "%3A")
      .replaceAll("\\;", "%3B")
      .replaceAll("\\=", "%3D")
      .replaceAll("\\@", "%40")
      .replaceAll("\\[", "%5B")
      .replaceAll("\\]", "%5D");
  }
1266913
def escape_string(value):
    
    res = StringIO()
    res.write('"')
    for c in value:
        if c in CHAR_TO_ESCAPE:
            res.write(f'\\{CHAR_TO_ESCAPE[c]}')
        elif c.isprintable():
            res.write(c)
        elif ord(c) < 0x100:
            res.write(f'\\x{ord(c):02x}')
        elif ord(c) < 0x10000:
            res.write(f'\\u{ord(c):04x}')
        else:
            res.write(f'\\U{ord(c):06x}')
    res.write('"')
    return res.getvalue()
73330
def _try_char(character, backup, encoding=sys.stdout.encoding):
    
    if character.encode(encoding, 'replace') == b'?':
        return backup
    else:
        return character
784344
def escape(s):
    """"""
    if not isinstance(s, bytes):
        s = s.encode('utf-8')
    return quote(s, safe='~')
476359
protected function _encodeString(&$string)
    {
        // Escape these characters with a backslash:
        // " \ / \n \r \t \b \f
        $search  = array('\\', "\n", "\t", "\r", "\b", "\f", '"');
        $replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\"');
        $string  = str_replace($search, $replace, $string);

        // Escape certain ASCII characters:
        // 0x08 => \b
        // 0x0c => \f
        $string = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);

        return '"' . $string . '"';
    }
1263938
def force_ascii_values(data):
    """"""
    return {
        k: v.encode('utf8').decode('ascii', 'backslashreplace')
        for k, v in data.items()
    }
241892
function toUnicode(charCode) {
    var result = charCode.toString(16).toUpperCase();
    while (result.length < 4) result = '0' + result;
    return '\\u' + result;
}
1330727
function(charCode)
	{
		var output = "";
		if (charCode>255) {
			output = "\\u"+(charCode<4096?"0":"")+charCode.toString(16);
		} else if (charCode>127) {
			output = "\\x"+charCode.toString(16);
		} else {
			output = (this.needsEscapingInCharClass(charCode)?"\\":"")+String.fromCharCode(charCode);
		}
		return output;
	}