Convert a Java variable containing a new line to a javascript variable


This question already has an answer here:

  • Escaping javascript string in java 2 answers

I want to convert a java variable(containing newline and other special characters) from server side sent to JSP to javascript variable.

In my JSP,

var test = '${educationDescription}';

Value of educationDescription sent from server side is

    This is
containing newline
and other special chars like " & ; etc

But I am getting javascript error for the above code snippet.

This issue I faced long back and very irritated with javascript as well for no proper error message.

Later I managed to solve by replacing all catridges like below from Java string.

<%@ taglib uri="" prefix="fn" %>

'${fn.replace(educationDescription,"\\r\\n|\\r|\\n", "")';

It solves the issue.

The issue here is with, we assume the problem is with new line. But sometimes the String comes with a brand new catride \r which many people not aware.