Method that will quote text contents using JSON standard quoting,
and return results as a character array
14569
public char[] quoteAsString(String input) {
        TextBuffer textBuffer = _textBuffer;
        if (textBuffer == null) {
            // no allocator; can add if we must, shouldn't need to
            _textBuffer = textBuffer = new TextBuffer(null);
        }
        char[] outputBuffer = textBuffer.emptyAndGetCurrentSegment();
        final int[] escCodes = sOutputEscapes128;
        final int escCodeCount = escCodes.length;
        int inPtr = 0;
        final int inputLen = input.length();
        int outPtr = 0;

        outer_loop: while (inPtr < inputLen) {
            tight_loop: while (true) {
                char c = input.charAt(inPtr);
                if (c < escCodeCount && escCodes[c] != 0) {
                    break tight_loop;
                }
                if (outPtr >= outputBuffer.length) {
                    outputBuffer = textBuffer.finishCurrentSegment();
                    outPtr = 0;
                }
                outputBuffer[outPtr++] = c;
                if (++inPtr >= inputLen) {
                    break outer_loop;
                }
            }
        // something to escape; 2 or 6-char variant?
        int escCode = escCodes[input.charAt(inPtr++)];
        int length = _appendSingleEscape(escCode, _quoteBuffer);
        if ((outPtr + length) > outputBuffer.length) {
            int first = outputBuffer.length - outPtr;
            if (first > 0) {
                System.arraycopy(_quoteBuffer, 0, outputBuffer, outPtr, first);
            }
            outputBuffer = textBuffer.finishCurrentSegment();
            int second = length - first;
            System.arraycopy(_quoteBuffer, first, outputBuffer, outPtr, second);
            outPtr += second;
        }
        else {
            System.arraycopy(_quoteBuffer, 0, outputBuffer, outPtr, length);
            outPtr += length;
        }

        }
        textBuffer.setCurrentLength(outPtr);
        return textBuffer.contentsAsArray();
    }
871996
def _get_json(value):
    """"""
    if hasattr(value, 'replace'):
        value = value.replace('\n', ' ')
    try:
        return json.loads(value)
    except json.JSONDecodeError:
        # Escape double quotes.
        if hasattr(value, 'replace'):
            value = value.replace('"', '\\"')
        # try putting the value into a string
        return json.loads('"{}"'.format(value))
921286
def quote_attrval (s):
    
    res = []
    for c in s:
        if ord(c) <= 127:
            # ASCII
            if c == u'&':
                res.append(u"&amp;")
            elif c == u'"':
                res.append(u"&quot;")
            else:
                res.append(c)
        else:
            res.append(u"&#%d;" % ord(c))
    return u"".join(res)
830861
private static String convertToQuotedString(String s) {
    if (s == null || s.isEmpty()) {
      return null;
    }
    // If already quoted, return as-is
    if (s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
      return s;
    }
    return '\"' + s + '\"';
  }
784344
def escape(s):
    """"""
    if not isinstance(s, bytes):
        s = s.encode('utf-8')
    return quote(s, safe='~')
1296945
function addQuotes(text, quoteChar) {
  var withquotes = text;
  if(!isQuotedString(text)) {
    var delim = quoteChar && quoteChar.length === 1 ? quoteChar : '"';
    withquotes = delim + text + delim;
  }
  return withquotes;
}
1011394
function (quoteSmart, tagName) {
            var start, state, done, quote, ch, end, comment, mCursor = this.cursor, mPage = this.page;
            start = mCursor.position;
            state = 0;
            done = false;
            quote = '';
            comment = false;
            while (!done) {
                ch = mPage.getChar(mCursor);
                switch (state) {
                case 0:
                    // prior to ETAGO
                    switch (ch) {
                    case -1:
                        done = true;
                        break;
                    case '\'':
                        if (quoteSmart && !comment) {
                            if ('' === quote) {
                                quote = '\'';    // enter quoted state
                            } else // enter quoted state
                            if ('\'' === quote) {
                                quote = '';    // exit quoted state
                            }
                        }
                        // exit quoted state
                        break;
                    case '"':
                        if (quoteSmart && !comment) {
                            if ('' === quote) {
                                quote = '"';    // enter quoted state
                            } else // enter quoted state
                            if ('"' === quote) {
                                quote = '';    // exit quoted state
                            }
                        }
                        // exit quoted state
                        break;
                    case '\\':
                        if (quoteSmart) {
                            if ('' !== quote) {
                                ch = mPage.getChar(mCursor);    // try to consume escaped character
                                // try to consume escaped character
                                if (NEGATIVE_1 === ch) {
                                    done = true;
                                } else if (ch !== '\\' && ch !== quote) {
                                    // unconsume char if character was not an escapable char.
                                    mPage.ungetChar(mCursor);
                                }
                            }
                        }
                        break;
                    case '/':
                        if (quoteSmart) {
                            if ('' === quote) {
                                // handle multiline and double slash comments (with a quote)
                                ch = mPage.getChar(mCursor);
                                if (NEGATIVE_1 === ch) {
                                    done = true;
                                } else if ('/' === ch) {
                                    comment = true;
                                } else if ('*' === ch) {
                                    do {
                                        do {
                                            ch = mPage.getChar(mCursor);
                                        } while (NEGATIVE_1 !== ch && '*' !== ch);
                                        ch = mPage.getChar(mCursor);
                                        if (ch === '*') {
                                            mPage.ungetChar(mCursor);
                                        }
                                    } while (NEGATIVE_1 !== ch && '/' !== ch);
                                } else {
                                    mPage.ungetChar(mCursor);
                                }
                            }
                        }
                        break;
                    case '\n':
                        comment = false;
                        break;
                    case '<':
                        if (quoteSmart) {
                            if ('' === quote) {
                                state = 1;
                            }
                        } else {
                            state = 1;
                        }
                        break;
                    default:
                        break;
                    }
                    break;
                case 1:
                    // <
                    switch (ch) {
                    case -1:
                        done = true;
                        break;
                    case '/':
                        // tagName = 'textarea'
                        // <textarea><div></div></textarea>
                        /*
                             8.1.2.6 Restrictions on the contents of raw text and RCDATA elements

                             The text in raw text and RCDATA elements must not contain any occurrences
                             of the string '</' (U+003C LESS-THAN SIGN, U+002F SOLIDUS)
                             followed by characters that case-insensitively match the tag name of the element
                             followed by one of U+0009 CHARACTER TABULATION (tab),
                             U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR),
                             U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).
                             */
                        if (!tagName || mPage.getText(mCursor.position, mCursor.position + tagName.length) === tagName && !mPage.getText(mCursor.position + tagName.length, mCursor.position + tagName.length + 1).match(/\w/)) {
                            state = 2;
                        } else {
                            state = 0;
                        }
                        break;
                    case '!':
                        ch = mPage.getChar(mCursor);
                        if (NEGATIVE_1 === ch) {
                            done = true;
                        } else if ('-' === ch) {
                            ch = mPage.getChar(mCursor);
                            if (NEGATIVE_1 === ch) {
                                done = true;
                            } else if ('-' === ch) {
                                state = 3;
                            } else {
                                state = 0;
                            }
                        } else {
                            state = 0;
                        }
                        break;
                    default:
                        state = 0;
                        break;
                    }
                    break;
                case 2:
                    // </
                    comment = false;
                    if (NEGATIVE_1 === ch) {
                        done = true;
                    } else if (Utils.isLetter(ch)) {
                        // 严格 parser 遇到 </x lexer 立即结束
                        // 浏览器实现更复杂点，可能 lexer 和 parser 混合了
                        done = true;    // back up to the start of ETAGO
                        // back up to the start of ETAGO
                        mPage.ungetChar(mCursor);
                        mPage.ungetChar(mCursor);
                        mPage.ungetChar(mCursor);
                    } else {
                        state = 0;
                    }
                    break;
                case 3:
                    // <!
                    comment = false;
                    if (NEGATIVE_1 === ch) {
                        done = true;
                    } else if ('-' === ch) {
                        ch = mPage.getChar(mCursor);
                        if (NEGATIVE_1 === ch) {
                            done = true;
                        } else if ('-' === ch) {
                            ch = mPage.getChar(mCursor);
                            if (NEGATIVE_1 === ch) {
                                done = true;
                            } else if ('>' === ch) {
                                // <!----> <!-->
                                state = 0;
                            } else {
                                // retreat twice , still begin to check -->
                                mPage.ungetChar(mCursor);
                                mPage.ungetChar(mCursor);
                            }
                        } else {
                            // retreat once , still begin to check
                            mPage.ungetChar(mCursor);
                        }
                    }    // eat comment
                    // eat comment
                    break;
                default:
                    throw new Error('unexpected ' + state);
                }
            }
            end = mCursor.position;
            return this.makeCData(start, end);
        }
1129601
def _parse_and_return_quoted_string(self):
        
        result = []
        pos = self.pos + 1
        segment_begin = pos
        my_chr = my_unichr if isinstance(self.text, my_unicode) else utf8chr
        while pos < self.end:
            c = self.text[pos]
            if c < ' ' and c != '\t':
                self.skip_to(pos)
                self.error('Encountered a control character that isn\'t allowed in quoted strings.')
            elif c == '"':
                if segment_begin < pos:
                    result.append(self.text[segment_begin:pos])
                pos += 1
                return ''.join(result), True, pos
            elif c == '\\':
                if segment_begin < pos:
                    result.append(self.text[segment_begin:pos])
                pos += 1
                if pos >= self.end:
                    break
                c = self.text[pos]
                if c == 'u':
                    code_point, pos = self._handle_unicode_escape(pos)
                    result.append(my_chr(code_point))
                else:
                    char, pos = self._handle_escape(pos, c)
                    result.append(char)
                segment_begin = pos
            else:
                pos += 1
        self.error('Reached the end of stream while parsing quoted string.')
939312
public static String quote(String s) {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            buf.append(quote(s.charAt(i)));
        }
        return buf.toString();
    }
1101398
function (quote) {
      var str;
      var n = this.html.indexOf(quote, this.currentChar);
      if (n === -1) {
        this.currentChar = this.html.length;
        str = null;
      } else {
        str = this.html.substring(this.currentChar, n);
        this.currentChar = n + 1;
      }

      return str;
    }
305599
private static EscapeStringResult escapeString(String s, char quote) {
        final String[] octal_strings = {
            "\\0",   "\\001", "\\002", "\\003", "\\004", "\\005", "\\006", "\\a",
            "\\b",   "\\t",   "\\n",   "\\v",   "\\f",   "\\r",   "\\016", "\\017",
            "\\020", "\\021", "\\022", "\\023", "\\024", "\\025", "\\026", "\\027",
            "\\030", "\\031", "\\032", "\\033", "\\034", "\\035", "\\036", "\\037",
        };

        StringBuilder result = new StringBuilder(s);
        boolean needQuotes = s.isEmpty();
        for (int i = 0, next_i; i < result.length(); i = next_i) {
            final int code_point = result.codePointAt(i);
            next_i = result.offsetByCodePoints(i, 1);

            if (code_point == 0) {
                result.replace(i, next_i, "\\0");
                next_i = i + 2;
                needQuotes = true;
            } else if (code_point == (int)'\\') {
                result.replace(i, next_i, "\\\\");
                next_i = i + 2;
                needQuotes = true;
            } else if (code_point == (int)quote) {
                result.replace(i, next_i, "\\" + quote);
                next_i = i + 2;
                needQuotes = true;
            } else if (code_point < 32) {
                String octal = octal_strings[code_point];
                result.replace(i, next_i, octal);
                next_i = i + octal.length();
                needQuotes = true;
            } else if (code_point >= 65536) {
                String repl = String.format("\\U%08x", code_point);
                result.replace(i, next_i, repl);
                next_i = i + repl.length();
                needQuotes = true;
            } else if (code_point >= 128) {
                String repl = String.format("\\u%04x", code_point);
                result.replace(i, next_i, repl);
                next_i = i + repl.length();
                needQuotes = true;
            }
        }
        return new EscapeStringResult(needQuotes, result);
    }
713038
def get_index_quote(self, code, as_json=False):
        
        url = self.index_url
        if self.is_valid_index(code):
            req = Request(url, None, self.headers)
            # raises HTTPError and URLError
            resp = self.opener.open(req)
            resp = byte_adaptor(resp)
            resp_list = json.load(resp)['data']
            # this is list of dictionaries
            resp_list = [self.clean_server_response(item)
                         for item in resp_list]
            # search the right list element to return
            search_flag = False
            for item in resp_list:
                if item['name'] == code.upper():
                    search_flag = True
                    break
            return self.render_response(item, as_json) if search_flag else None
1174436
public JSONBuilder quote(String value) {
        _sb.append('"');
        for (int i = 0; i < value.length(); ++i) {
            char c = value.charAt(i);
            switch (c) {
            case '"':
                _sb.append("\\\"");
                break;
            case '\\':
                _sb.append("\\\\");
                break;
            default:
                if (c < 0x20) {
                    _sb.append(CTRLCHARS[c]);
                } else {
                    _sb.append(c);
                }
                break;
            }
        }
        _sb.append('"');
        return this;
    }
361319
function (vValue) {
			var sStringified,
				bEscaped = false,
				sResult = "",
				i, c;

			sStringified = JSON.stringify(vValue);
			if (sStringified === undefined) {
				return undefined;
			}
			for (i = 0; i < sStringified.length; i += 1) {
				switch (c = sStringified.charAt(i)) {
					case "'": // a single quote must be escaped (can only occur in a string)
						sResult += "\\'";
						break;
					case '"':
						if (bEscaped) { // a double quote needs no escaping (only in a string)
							sResult += c;
							bEscaped = false;
						} else { // string begin or end with single quotes
							sResult += "'";
						}
						break;
					case "\\":
						if (bEscaped) { // an escaped backslash
							sResult += "\\\\";
						}
						bEscaped = !bEscaped;
						break;
					default:
						if (bEscaped) {
							sResult += "\\";
							bEscaped = false;
						}
						sResult += c;
				}
			}
			return sResult;
		}
1125035
public static String escape(String value, char quote) {
    Map<CharSequence, CharSequence> lookupMap = new HashMap<>();
    lookupMap.put(Character.toString(quote), "\\" + quote);
    lookupMap.put("\\", "\\\\");

    final CharSequenceTranslator escape =
        new LookupTranslator(lookupMap)
                .with(new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE))
                .with(JavaUnicodeEscaper.outsideOf(32, 0x7f));

    return quote + escape.translate(value) + quote;
  }
442975
private String quotedAV() {
    pos++;
    beg = pos;
    end = beg;
    while (true) {

      if (pos == length) {
        throw new IllegalStateException("Unexpected end of DN: " + dn);
      }

      if (chars[pos] == '"') {
        // enclosing quotation was found
        pos++;
        break;
      } else if (chars[pos] == '\\') {
        chars[end] = getEscaped();
      } else {
        // shift char: required for string with escaped chars
        chars[end] = chars[pos];
      }
      pos++;
      end++;
    }

    // skip trailing space chars before comma or semicolon.
    // (compatibility with RFC 1779)
    for (; pos < length && chars[pos] == ' '; pos++) {
    }

    return new String(chars, beg, end - beg);
  }
859167
def quote_from_bytes(bs, safe='/'):
    
    if not isinstance(bs, (bytes, bytearray)):
        raise TypeError("quote_from_bytes() expected bytes")
    if not bs:
        return str('')
    ### For Python-Future:
    bs = bytes(bs)
    ###
    if isinstance(safe, str):
        # Normalize 'safe' by converting to bytes and removing non-ASCII chars
        safe = str(safe).encode('ascii', 'ignore')
    else:
        ### For Python-Future:
        safe = bytes(safe)
        ###
        safe = bytes([c for c in safe if c < 128])
    if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
        return bs.decode()
    try:
        quoter = _safe_quoters[safe]
    except KeyError:
        _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
    return str('').join([quoter(char) for char in bs])