Tell me, who knows how to replace '>' with '& gt;' in the block with the text?
5 answers
var str = "<div id = 'code'><p>ТЕКСТ</p></div>"; console.log(str.replace(/</g, '<').replace(/>/g, '>')); // <div id = 'code'><p>ТЕКСТ</p></div>
Solution of your question:
var code = $('#code'); code.html( code.html() .replace(/</g, '<') .replace(/>/g, '>') )
- @Deonis for what minus please explain. - FLK
|
PHP showed you @ROOT . If on JS, then so
var str = "adcdefg>abcdefg"; alert(str.replace('>','>'));
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("&", "<", ">", """, "'"); 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
- oneOh, 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 )); // -> <h1>evil html</h1> console.log(htmlentities( evilScript )); // -> <script> alert('evil script') </script>
- Lol, called all cyclists. Plus) - Sh4dow
|
str_replace(">",">",$text);
|
Why all this thing is forgotten?)
var newStr = oldStr.split('<').join('<');
Or:
var newStr = oldStr; var replaces = [ '<': '<', '>': '>' // , '&': '&', 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
|