JQuery Text Replacement

Who knows how to replace ‘>’ to ‘>’ in a block with text?


Answer 1, authority 100%

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 to your question:

var code = $('#code');
code.html(
  code.html()
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
)

Answer 2, authority 100%

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

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

UPDHere we need something like PHP’s 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>

Answer 3, authority 50%

(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;

Answer 4

str_replace(">","&gt;",$text);

Answer 5

Why does everyone forget this thing?)

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]);

Leave a reply

Please enter your comment!
Please enter your name here