unterminated string constant

G

Guest

From server-side code I'm using Response.Write to display a javascript alert
box. It works fine except when I try to include a new line character, which
causes this javascript error:

"Unterminated string constant"

Here's my c# code:

strText = "Line 1 text\nLine2 text";
Response.Write("<script>alert('" + strText + "');</script>");

Any ideas how to get around this problem?
 
G

Guest

Thanks for the response. I understand that there are other ways to call a
javascript function. But this way works fine for most things. Do you know
why the new line doesn't work here?
 
S

Siva M

List 1 text should end with '\' character if the string constant continued
on a new line: Try strText = "Line 1 text\\\nLine2 test";

From server-side code I'm using Response.Write to display a javascript alert
box. It works fine except when I try to include a new line character, which
causes this javascript error:

"Unterminated string constant"

Here's my c# code:

strText = "Line 1 text\nLine2 text";
Response.Write("<script>alert('" + strText + "');</script>");

Any ideas how to get around this problem?
 
L

Laurent Bugnion

Hi,

ken said:
From server-side code I'm using Response.Write to display a javascript alert
box. It works fine except when I try to include a new line character, which
causes this javascript error:

"Unterminated string constant"

Here's my c# code:

strText = "Line 1 text\nLine2 text";
Response.Write("<script>alert('" + strText + "');</script>");

Any ideas how to get around this problem?

Make a view-source on the produced HTML code. You will see this:

<script>alert('Line 1 text
Line2 text');</script>

This is illegal JavaScript. Unlike HTML, JavaScript strings cannot be
spread one more than one line without being closed.

What you want is this:

<script>alert('Line 1 text\nLine 2 text');</script>

which in the code behind translates to:

Response.Write( "<script>alert('Line 1 text\\nLine 2 text');</script>" );

HTH,
Laurent
 
L

Laurent Bugnion

Hi,

Siva said:
List 1 text should end with '\' character if the string constant continued
on a new line: Try strText = "Line 1 text\\\nLine2 test";

Too many '\'.

See my post.
Laurent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top