0

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}';
alert(test);

Value of educationDescription sent from server side is

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

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

5
  • 1
    You already did it. What is your question ? Commented Sep 5, 2014 at 8:19
  • 1
    Hi Suresh, I am getting javascript error for the above code since in javascript, its a string var spanning in more than 1 line. Commented Sep 5, 2014 at 8:21
  • As this is a variable which is containing new lines, you need to escape new line. Commented Sep 5, 2014 at 8:31
  • 1
    Have you tried using StringEscapeUtils.escapeJavaScript from Apache's common-lang lib? Commented Sep 5, 2014 at 8:40
  • @Jai I gave an answer :) Can you check and let me know ? Commented Sep 5, 2014 at 8:42

2 Answers 2

0

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="http://java.sun.com/jsp/jstl/functions" 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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this. Use two slashes ("\\n")

<%
String s = "This is a \\n test";
request.setAttribute("s", s);
%>

var s="${s}";
alert(s);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.