Java String Quote quote(String text)

Here you can find the source of quote(String text)

Description

Quotes the provided value as a JavaScript string literal.

License

Apache License

Parameter

Parameter Description
text a parameter

Return

quoted text

Declaration

public static String quote(String text) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

public class Main {
    static final char APOS = '\'';
    static final char QUOTE = '"';
    static final char SLASH = '\\';

    /**/*from   w w  w.  j  a  va  2s  .com*/
     * Quotes the provided value as a JavaScript string literal. The input value is surrounded by single quotes and any
     * interior backslash, single or double quotes are escaped (a preceding backslash is added).
     *
     * @param text
     * @return quoted text
     */
    public static String quote(String text) {
        StringBuilder result = new StringBuilder(text.length() * 2);

        result.append(APOS);

        for (char ch : text.toCharArray()) {
            switch (ch) {
            case APOS:
            case QUOTE:
            case SLASH:

                result.append(SLASH);

            default:
                result.append(ch);
                break;
            }
        }

        result.append(APOS);

        return result.toString();
    }
}

Related

  1. quote(String tableName)
  2. quote(String text)
  3. quote(String text)
  4. quote(String text)
  5. quote(String text)
  6. quote(String text)
  7. quote(String text, String quote)
  8. quote(String toQuote, String specials, char quoteChar)
  9. quote(String txt)