Tell me, who knows how to replace '>' with '& gt;' in the block with the text?

    5 answers 5

    var str = "<div id = 'code'><p>ТЕКСТ</p></div>"; console.log(str.replace(/</g, '&lt;').replace(/>/g, '&gt;')); // &lt;div id = 'code'&gt;&lt;p&gt;ТЕКСТ&lt;/p&gt;&lt;/div&gt; 

    Solution of your question:

     var code = $('#code'); code.html( code.html() .replace(/</g, '&lt;') .replace(/>/g, '&gt;') ) 
    • @Deonis for what minus please explain. - FLK

    PHP showed you @ROOT . If on JS, then so

     var str = "adcdefg>abcdefg"; alert(str.replace('>','&gt;')); 

    UPD Here you need something like php-shny htmlspecialchars (). See how it works .

     <div id = "code"> <p>ТЕКСТ</p> <span>UPS</span> <div>Hashcode</div> </div> <div id = "res"><strong>Результат: </strong></div> <script> function htmlspecialchars(text) { var chars = Array("&", "<", ">", '"', "'"); var replacements = Array("&amp;", "&lt;", "&gt;", "&quot;", "'"); for (var i=0; i<chars.length; i++) { var re = new RegExp(chars[i], "gi"); if(re.test(text)) { text = text.replace(re, replacements[i]); } } return text; } var content = $('#code').html(); var newStr = htmlspecialchars(content); $('#res').append(newStr); </script> 
    • if I allow it in <div id = 'code'> <p> TEXT </ p> </ div> And I need to change it so that it changes to <div id = 'code'> & gt; p & gt; TEXT & lt; / p & gt; </ div> how to be? - zhekonya
    • @zhekonya, see the update in response - Deonis
    • Both options are non-working. the first one will change only one character, the second one will return only the content of the diva #code and also change only one character at a time - FLK
    • First, the first option was before the clarification. Secondly, it is the contents of the diva # code and must be converted into mnemonics. Shrewd, but not attentive. - Deonis
    • one
      Oh, sir, do me a favor - instead of looking for something to find fault, just give me a minus and don't tire. Yep - Deonis
     (function(w, d) { var t = d.createElement("div"); w.htmlentities = function(s) { t.innerHTML = ''; t.appendChild(d.createTextNode(s)); return t.innerHTML; } }(window, document)); var evilHtml = "<h1>evil html</h1>" var evilScript = "<script> alert('evil script') </script>" console.log(htmlentities( evilHtml )); // -> &lt;h1&gt;evil html&lt;/h1&gt; console.log(htmlentities( evilScript )); // -> &lt;script&gt; alert('evil script') &lt;/script&gt; 
    • Lol, called all cyclists. Plus) - Sh4dow
     str_replace(">","&gt;",$text); 

      Why all this thing is forgotten?)

       var newStr = oldStr.split('<').join('&lt;'); 

      Or:

       var newStr = oldStr; var replaces = [ '<': '&lt;', '>': '&gt;' // , '&': '&amp;', etc etc... ]; for (var n in replaces) newStr = newStr.split(n).join(replaces[n]); 
      • oldStr.split ('<'). join ('& lt;'); Inadequate in performance and readability, the second is even worse than the first. - Zowie
      • replace with regulars in a loop is it better?) - Sh4dow