How do I escape a String for JavaScript?
Author: Deron Eriksson
Description: This Java example shows how to escape a String for JavaScript using StringEscapeUtils.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The escapeJavaScript() method of the StringEscapeUtils class in the Commons LangS library makes it easy to escape a String for JavaScriptW. It takes the String to escape as a parameter and returns the JavaScript-escaped String. This method performs like escapeJava() except that it also escapes single quotes. JavaScriptEscapeTest demonstrates this. It reads a String of text from the input.txt file using FileUtils from Commons IOS, JavaScript escapes the String, and displays the results to the console.

JavaScriptEscapeTest.java

package test;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;

public class JavaScriptEscapeTest {

	public static void main(String[] args) throws Exception {

		String str = FileUtils.readFileToString(new File("input.txt"));
		String results = StringEscapeUtils.escapeJavaScript(str);
		System.out.println(results);

	}

}

The input.txt file is shown here.

input.txt

	Here is some "Text" that
I'd like to be "escaped" for JavaScript.
I'll try a couple special characters here: \ "

The results are shown below.

Results

\tHere is some \"Text\" that\r\nI\'d like to be \"escaped\" for JavaScript.\r\nI\'ll try a couple special characters here: \\ \"