jQuery或vanilla JavaScript:替换或转义所有<和>

时间:2017-10-02 01:59:51

标签: javascript jquery

我有这样的div

<div id="asdf">
  <div>
    <p>ASDF IS AWESOME</p>
  </div>
  <h1>Just another Headline</h1>
  <nav>
    <ul>
      <li class="listitem">Hey</li>
    </ul>
  </nav>
</div>

并需要一个jQueryvanilla JavaScript函数,将整个内容转换为此

的方法
&lt;div id="asdf"
  &lt;div&gt;
    &lt;p>ASDF IS AWESOME&lt;/p&gt;
  &lt;/div&gt;
  &lt;h1>Just another Headline&lt;/h1&gt;
  &lt;nav&gt;
    &lt;ul&gt;
      &lt;li class="listitem"Hey&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/nav&gt;
&lt;/div&gt;

所以我只想逃避<>

我尝试了.replace.text()

2 个答案:

答案 0 :(得分:3)

试试

&#13;
&#13;
var html = $('#asdf').html();
var escaped=$('<div/>').text(html).html();
console.log(escaped);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="asdf">
  <div>
    <p>ASDF IS AWESOME</p>
  </div>
  <h1>Just another Headline</h1>
  <nav>
    <ul>
      <li class="listitem">Hey</li>
    </ul>
  </nav>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:只使用1个功能,然后就可以在任何地方使用

$(document).ready(function(){
  $selector = $('#asdf');      
  console.log(htmlEntities($selector));
  function htmlEntities(str) {
    str = str.html();
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="asdf">
  <div>
    <p>ASDF IS AWESOME</p>
  </div>
  <h1>Just another Headline</h1>
  <nav>
    <ul>
      <li class="listitem">Hey</li>
    </ul>
  </nav>
</div>

您可以参考:https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/