javascript對文本encode編碼

來源:互聯網
上載者:User

         //source輸入的文本
   //dispaly爲true,表示格式化特殊字元,如把輸入的空格替換成&nbsp;換行替(\r\n))換成<br>
   //tabs默認爲4
  function htmlEncode(source, display, tabs)
  {
   function special(source)
   {
    var result = '';
    for (var i = 0; i < source.length; i++)
    {
     var c = source.charAt(i);
     if (c < ' ' || c > '~')
     {
      c = '' + c.charCodeAt() + ';';
     }
     result += c;
    }
    return result;
   }
   
   function format(source)
   {
    // Use only integer part of tabs, and default to 4
    tabs = (tabs >= 0) ? Math.floor(tabs) : 4;
    
    // split along line breaks
    var lines = source.split(/\r\n|\r|\n/);
    
    // expand tabs
    for (var i = 0; i < lines.length; i++)
    {
     var line = lines[i];
     var newLine = '';
     for (var p = 0; p < line.length; p++)
     {
      var c = line.charAt(p);
      if (c === '\t')
      {
       var spaces = tabs - (newLine.length % tabs);
       for (var s = 0; s < spaces; s++)
       {
        newLine += ' ';
       }
      }
      else
      {
       newLine += c;
      }
     }
     // If a line starts or ends with a space, it evaporates in html
     // unless it's an nbsp.
     newLine = newLine.replace(/(^ )|( $)/g, '&nbsp;');
     lines[i] = newLine;
    }
    
    // re-join lines
    var result = lines.join('<br />');
    
    // break up contiguous blocks of spaces with non-breaking spaces
    result = result.replace(/  /g, ' &nbsp;');
    
    // tada!
    return result;
   }

   var result = source;
   
   // ampersands (&)
   result = result.replace(/\&/g,'&amp;');

   // less-thans (<)
   result = result.replace(/\</g,'&lt;');

   // greater-thans (>)
   result = result.replace(/\>/g,'&gt;');
   
   if (display)
   {
    // format for display
    result = format(result);
   }
   else
   {
    // Replace quotes if it isn't for display,
    // since it's probably going in an html attribute.
    result = result.replace(new RegExp('"','g'), '&quot;');
   }

   // special characters
   result = special(result);
   
   // tada!
   return result;
  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.