-3

I applied this answer in project, I need to escape both at client and server:

function replaceTag(tag) {
        var tagsToReplace = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;"
        };
        return tagsToReplace[tag] || tag;
    }

    function safe_tags_replace(str) {
        var self = this;
        return str.replace(/[&<>]/g, self.replaceTag);
    }
    
    var result = safe_tags_replace(">");
    result = safe_tags_replace(result);
    console.log(result);

How can I make special character > is "escaped" to &gt; instead of &amp;gt;

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84

2 Answers2

0

There's no need to reinvent the wheel here. If you just need to display text without rendering HTML, use a built-in escape mechanism like this:

var
  input = document.getElementById('input'),
  chat = document.getElementById('chat');

input.addEventListener('keypress', function(event) {
  if ((event.keyCode || event.which) === 13) {
    var msg = document.createElement('div');

    msg.textContent = input.value;
    // msg.appendChild(document.createTextNode(input.value));

    input.value = '';

    chat.appendChild(msg);
  }
});
<div id="chat"></div>
<input id="input" type="text" value="&lt;script&gt;alert('dangerous');&lt;/script&gt;"/>

Press Enter and see what happens. I dare you.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
-1

Try this regex:

/[<>]|&(?!amp;|gt;|lt;)/g

using it like this:

str.replace(/[<>]|&(?!amp;|gt;|lt;)/g, self.replaceTag);
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • @asdf_enel_hak Use this regex in `str.replace`, I've updated the code. It will replace `&` only if not followed by `amp;` `gt;` or `lt;`. – jcubic Jan 25 '16 at 09:07