• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1391
  • Last Modified:

New Line in Javascript Alert

I'm writing out some javascript code in my
servlet, and if I put a "\n" into my code -
I get a undetermined string error.  If I take
it out, it works fine.

Here's sample code:

 public void doGet (HttpServletRequest request, HttpServletResponse response)
                                                                      throws ServletException, IOException{
             PrintWriter      out;         
       // set content type and other response header fields first
           // then write the data of the response
       out = response.getWriter();

             // html text ........................

            out.println("<SCRIPT language=\"JavaScript\">");
            out.println("function Warning(war, war1){");
            out.println("if(war == \"\" || war1 == -1) {");
     ??? out.println("alert(\"1. Save As \n 2.Open \" );");
            out.println("return (false);");
       out.println("else {");
      out.println("return (true);");
      out.println("}  }");

            // html text.........................
  • 2
1 Solution
out.println("alert(\"1. Save As \\n 2.Open \" );");
You must escape the backslash with a backslash, otherwise the newline character is written to the alert statement, instead of the text that the alert is supposed to display.  For example, your code above would output this:

 alert("1. Save As
 2. Open");

instead of:

 alert("1. Save As \n2. Open");

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now