/*
* Enhydra Java Application Server Project
*
* The contents of this file are subject to the Enhydra Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License on
* the Enhydra web site ( http://www.enhydra.org/ ).
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific terms governing rights and limitations
* under the License.
*
* The Initial Developer of the Enhydra Application Server is Lutris
* Technologies, Inc. The Enhydra Application Server and portions created
* by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
* All Rights Reserved.
*
* Contributor(s):
*
* $Id: JavaScriptEncoder.java,v 1.15 2005/06/13 09:26:06 draganr Exp $
*/
package com.lutris.util;
/**
* This class contains a utility method for encoding a
* <code>String</code> so that it may be safely used
* within JavaScript as a quoted string.
*
* The following characters are encoded:
* <p>
* <ul>
* <li> '
* <li> "
* <li> \
* </ul>
*
* @author Kyle Clark
*/
public class JavaScriptEncoder {
/**
* Translates a string into a JavaScript safe format.
*
* @param s the string to encode
* @return the encoded string
*/
public static String encode(String s) {
char [] scriptChars = s.toCharArray();
StringBuffer encodedScript = new StringBuffer();
for (int i=0; i<scriptChars.length; i++) {
switch(scriptChars[i]) {
case '\'':
encodedScript.append("\\\'");
break;
case '\"':
encodedScript.append("\\\"");
break;
case '\\':
encodedScript.append("\\\\");
break;
default:
encodedScript.append(scriptChars[i]);
break;
}
}
return encodedScript.toString();
}
}