KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > util > JavaScriptEncoder


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  *
22  * $Id: JavaScriptEncoder.java,v 1.1 2004/04/21 19:31:58 slobodan Exp $
23  */

24
25
26
27
28 package com.lutris.util;
29
30 /**
31  * This class contains a utility method for encoding a
32  * <code>String</code> so that it may be safely used
33  * within JavaScript as a quoted string.
34  *
35  * The following characters are encoded:
36  * <p>
37  * <ul>
38  * <li> &#39;
39  * <li> &quot;
40  * <li> &#92;
41  * </ul>
42  *
43  * @author Kyle Clark
44  */

45 public class JavaScriptEncoder {
46
47     /**
48      * Translates a string into a JavaScript safe format.
49      *
50      * @param s the string to encode
51      * @return the encoded string
52      */

53     public static String JavaDoc encode(String JavaDoc s) {
54         char [] scriptChars = s.toCharArray();
55         StringBuffer JavaDoc encodedScript = new StringBuffer JavaDoc();
56         for (int i=0; i<scriptChars.length; i++) {
57             switch(scriptChars[i]) {
58             case '\'':
59                 encodedScript.append("\\\'");
60                 break;
61             case '\"':
62                 encodedScript.append("\\\"");
63                 break;
64             case '\\':
65                 encodedScript.append("\\\\");
66                 break;
67             default:
68                 encodedScript.append(scriptChars[i]);
69                 break;
70             }
71         }
72         return encodedScript.toString();
73     }
74 }
75
Popular Tags