views:

73

answers:

2

HI, using C# I am saving formated HTML data in MSSQL such as:

<div>\n\t<p>x</p>\n</div>

I am than populating it into a textarea to display. I understand that I can use the .val() method in jQuery to pull all of the ASCII characters out of the textarea, however, I can't seem to figure out how to get the "\n" and "\t" characters to show up as new lines and tabs.

When I use FireBug to check the html contents of the textarea in question, this is what is displayed:

&lt;div&gt;/\n/\t&lt;p&gt;This is a test Div&lt;/p&gt;/\n&lt;/div&gt;

I don't really care about using jQuery to display the new lines and tabs, I can also use .NET to change the characters, I would just like to know either or both options.

Thanks much!

+1  A: 

In .NET you can use String.Replace:

s = s.Replace(@"\n", "\n");
s = s.Replace(@"\t", "\t");

You might want to consider whether you should make this replacement before you insert the data into the database rather than as you fetch it, because you'll probably only be inserting it once but fetching it a lot of times.

On the other hand, if you do it on the client then the work is offloaded from the server. But if they don't have Javascript enabled, it will look wrong.

Mark Byers
jeeez man... not even a 5 minutes wait. WOW! I will try, thanks!
Tomaszewski
Did you have any luck with it?
Mark Byers
@Tomaszewski: `"\n"` is ((char)10) and `"\r"` is ((char)13), but what I told you should work. It sounds like you have a bug elsewhere in your program. Have you tried stepping through your code line by line to see where the problem occurs?
Mark Byers
yes, that worked perfect and you are right about altering the data upon insertion instead of retrieval. Thanks much!
Tomaszewski
Mark, I did... and didn't realize that problem. I wrote the old comment but then deleted it because I realized I wasn't assigning the replacement to another string (or itself) as in (s = s...). Thanks for the character codes too. That made it all complete.
Tomaszewski
@Tomaszewski: Ah yep, that's a quite common mistake. Strings are immutable, so replace returns a new string rather than modifying the original. Shame the compiler doesn't give a warning if you use replace without using the result.
Mark Byers
just a small addition to this, you gave me the ascii codes for \r which is a carriage return and the ascii code is 13. For a horizontal tab (\t), the ascii code is 11.
Tomaszewski
Sorry, I forgot which characters you wanted. And by the way, "\t" is 9 not 11.
Mark Byers
+3  A: 

You should be saving your data better than that... but for now, you can use a simple regex trick:

yourString.replace(/\\n/g, "\n").replace(/\\t/g, "\t");
Avindra Goolcharan