01: /*
02: * Enhydra Java Application Server Project
03: *
04: * The contents of this file are subject to the Enhydra Public License
05: * Version 1.1 (the "License"); you may not use this file except in
06: * compliance with the License. You may obtain a copy of the License on
07: * the Enhydra web site ( http://www.enhydra.org/ ).
08: *
09: * Software distributed under the License is distributed on an "AS IS"
10: * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11: * the License for the specific terms governing rights and limitations
12: * under the License.
13: *
14: * The Initial Developer of the Enhydra Application Server is Lutris
15: * Technologies, Inc. The Enhydra Application Server and portions created
16: * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17: * All Rights Reserved.
18: *
19: * Contributor(s):
20: *
21: * $Id: JavaScriptEncoder.java,v 1.2 2006-06-15 13:47:01 sinisa Exp $
22: */
23:
24: package com.lutris.util;
25:
26: /**
27: * This class contains a utility method for encoding a
28: * <code>String</code> so that it may be safely used
29: * within JavaScript as a quoted string.
30: *
31: * The following characters are encoded:
32: * <p>
33: * <ul>
34: * <li> '
35: * <li> "
36: * <li> \
37: * </ul>
38: *
39: * @author Kyle Clark
40: */
41: public class JavaScriptEncoder {
42:
43: /**
44: * Translates a string into a JavaScript safe format.
45: *
46: * @param s the string to encode
47: * @return the encoded string
48: */
49: public static String encode(String s) {
50: char[] scriptChars = s.toCharArray();
51: StringBuffer encodedScript = new StringBuffer();
52: for (int i = 0; i < scriptChars.length; i++) {
53: switch (scriptChars[i]) {
54: case '\'':
55: encodedScript.append("\\\'");
56: break;
57: case '\"':
58: encodedScript.append("\\\"");
59: break;
60: case '\\':
61: encodedScript.append("\\\\");
62: break;
63: default:
64: encodedScript.append(scriptChars[i]);
65: break;
66: }
67: }
68: return encodedScript.toString();
69: }
70: }
|