KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > util > JavaScriptUtils


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.util;
18
19 /**
20  * Utility class for JavaScript escaping.
21  * Escapes based on the JavaScript 1.5 recommendation.
22  *
23  * <p>Reference:
24  * <a HREF="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Literals#String_Literals">
25  * Core JavaScript 1.5 Guide
26  * </a>
27  *
28  * @author Juergen Hoeller
29  * @author Rob Harrop
30  * @since 1.1.1
31  */

32 public class JavaScriptUtils {
33
34     /**
35      * Turn special characters into escaped characters conforming to JavaScript.
36      * Handles complete character set defined in HTML 4.01 recommendation.
37      * @param input the input string
38      * @return the escaped string
39      */

40     public static String JavaDoc javaScriptEscape(String JavaDoc input) {
41         if (input == null) {
42             return input;
43         }
44
45         StringBuffer JavaDoc filtered = new StringBuffer JavaDoc(input.length());
46         char prevChar = '\u0000';
47         char c;
48         for (int i = 0; i < input.length(); i++) {
49             c = input.charAt(i);
50             if (c == '"') {
51                 filtered.append("\\\"");
52             }
53             else if (c == '\'') {
54                 filtered.append("\\'");
55             }
56             else if (c == '\\') {
57                 filtered.append("\\\\");
58             }
59             else if (c == '/') {
60                 filtered.append("\\/");
61             }
62             else if (c == '\t') {
63                 filtered.append("\\t");
64             }
65             else if (c == '\n') {
66                 if (prevChar != '\r') {
67                     filtered.append("\\n");
68                 }
69             }
70             else if (c == '\r') {
71                 filtered.append("\\n");
72             }
73             else if (c == '\f') {
74                 filtered.append("\\f");
75             }
76             else {
77                 filtered.append(c);
78             }
79             prevChar = c;
80
81         }
82         return filtered.toString();
83     }
84
85 }
86
Popular Tags