Java Script escapeJavascript(String str)

Here you can find the source of escapeJavascript(String str)

Description

Encoding if need escaping %$&+,/:;=?@<>#%

License

Open Source License

Parameter

Parameter Description
str should be encoded

Return

encoded Result

Declaration

public static String escapeJavascript(String str) 

Method Source Code

//package com.java2s;

import java.util.HashMap;

import java.util.Map.Entry;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {
    private static final ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    private static final HashMap<String, String> jsReplaces = new HashMap<>();

    /**//from   w w  w  .  j a  v a2  s  .com
     * Encoding if need escaping %$&+,/:;=?@<>#%
     *
     * @param str should be encoded
     *
     * @return encoded Result
     */
    public static String escapeJavascript(String str) {
        try {
            String n = engine.eval(String.format("escape(\"%s\")", str.replaceAll("%20", " "))).toString();
            for (Entry<String, String> e : jsReplaces.entrySet()) {
                n = n.replaceAll(e.getKey(), e.getValue());
            }
            return n;
        } catch (ScriptException ex) {
            return null;
        }
    }
}

Related

  1. adjustKey(String key)
  2. cdInShell(IResource resource)
  3. convert(Object from)
  4. dbObjectFromMap(Map from)
  5. decodeB64_TO_UTF8(String encodedStr)
  6. eval(String expression, Object... arguments)
  7. eval(String name, Map params)
  8. eval(String script)
  9. evaluateExpression(String expr)