Java Custom addSlashes()

October 1, 2010 at 06:56 (java, javascript, tutorial, web dev)

Java regexes can get pretty clunky due to the dual use of the backslash character, as is commonly known. Although there’s not a lot to it, below is some code to add slashes for these characters: backslash, line feed, carriage return, null, single quote. It is used in a web application to format JSON strings on the server before passing to the client, where the objects are then processed by JavaScript/Ext JS. Maybe someone will find it useful!

public class StringUtil {
    public static String addSlashes(String s) {
        s = s.replaceAll("\\\\", "\\\\\\\\");
        s = s.replaceAll("\\n", "\\\\n");
        s = s.replaceAll("\\r", "\\\\r");
        s = s.replaceAll("\\00", "\\\\0");
        s = s.replaceAll("'", "\\\\'");
        return s;
    }
}

Incidentally, there are other places where the following JavaScript replacement is necessary:

s = s.replace(/"/g, '"');
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: