01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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 javaScriptEscape(String input) {
41: if (input == null) {
42: return input;
43: }
44:
45: StringBuffer filtered = new StringBuffer(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: } else if (c == '\'') {
53: filtered.append("\\'");
54: } else if (c == '\\') {
55: filtered.append("\\\\");
56: } else if (c == '/') {
57: filtered.append("\\/");
58: } else if (c == '\t') {
59: filtered.append("\\t");
60: } else if (c == '\n') {
61: if (prevChar != '\r') {
62: filtered.append("\\n");
63: }
64: } else if (c == '\r') {
65: filtered.append("\\n");
66: } else if (c == '\f') {
67: filtered.append("\\f");
68: } else {
69: filtered.append(c);
70: }
71: prevChar = c;
72:
73: }
74: return filtered.toString();
75: }
76:
77: }
|