开发者

C# method to convert html-markup into JavaScript-compatible string

I believe there should exist a known method for converting this:

   <div class="singlePane pane">
     <div class="tripleColumn"> <!-- TODO:  -->
     <div cla开发者_StackOverflow中文版ss="col">

    <div class="captionedLink">
     <div class="icon" style="background-position: -26px 0px;"> blah blah

INTO THIS:

    \r\n \u003Cdiv class=\"singlePane pane\"\u003E\r\n \u003Cdiv class=\"tripleColumn
\"\u003E \u003C!-- TODO --\u003E\r\n \u003Cdiv class=\"col\"\u003E\r\n 
\n\u003Cdiv class=\"captionedLink\"\u003E\n \u003Cdiv class=\"icon\" style=\"background-
position: -26px 0px\"\uBLAH BLAH

Please, please reveal it to me.

Thanks in advance!


I'm currently using (a slightly modified version of) Rick Strahl's JavaScript encoding. Works well for me!


This is by no means the fastest way to do this (static Regex.Replace method is slow compared to a Regex instance. But I've done this in order to turn any html into a string that can be used for document.write:

string htmlResult = "/*string*/";
htmlResult = Regex.Replace(htmlResult, @"\r\n", " ");
htmlResult = Regex.Replace(htmlResult, @"\n", " ");
htmlResult = Regex.Replace(htmlResult, @"\s{2,}", " ");
htmlResult = Regex.Replace(htmlResult, @"\\", @"\\");
htmlResult = Regex.Replace(htmlResult, @"[']", @"\'");

This also does away with all your carriage returns and unnecessary whitespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜