简体   繁体   中英

How to get String from C# with \r to JavaScript variable?

I write program with aspx and C# in VS2010. I want to alert all the SoftWareNotes in loop. (it's a varchar value in my DB). so I did that:

<% for(Software s in Db.Softwares){ %>
<script>
            var GetTextArea= '<%=s.SoftwareNotes%>' ;
            alert(GetTextArea);
</script>
<%}%>

and it's work fine , until that SoftwareNotes contain /r . for example in this string: "fdbdfb\\r\\ndfbdf\\r\\ndfb" (from the debugger) , it's not print nothing, and continue to the next one.

Why and how can I fix that?

*The field SoftwareNotes contain /r cause it's populate by TextAreas ..so if someone make enter it save it like a /r.


edit 2:20: I found one solution , but it's not the best.. I write this code above the code before:

 <%
                String tryRemoveNL="";
                if(s.SoftwareNotes!=null)
                    tryRemoveNL= Regex.Replace(s.SoftwareNotes, @"\r\n?|\n", " ");
                 %>

and now when I write:

var GetTextArea= '<%=tryRemoveNL%>' ;

it works. but I want to keep the newLines.. maybe you have other solutions?

It's possible to do it using the following:

var GetTextArea= '<%=s.SoftwareNotes.Replace(Environment.NewLine, "\\r\\n"))%>' ;
alert(GetTextArea);

This keeps the line breaks within the alert message.

The issue was because the literal linebreaks were coming through into the javascript, creating invalid syntax , similar to:

var GetTextArea = 'fdbdfb
dfbdf
dfb'; //Invalid syntax for multiline javascript string

So instead, this solution will write out:

var GetTextArea = 'fdbdfb\r\ndfbdf\r\ndfb'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM