Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting HTML to its safe entities with Javascript

I'm trying to convert characters like < and > into &lt; and &gt; etc.

User input is taken from a text box, and then copied into a DIV called changer.

here's my code:

function updateChanger() {
    var message = document.getElementById('like').value;
    message = convertHTML(message);
    document.getElementById('changer').innerHTML = message;
}

function convertHTML(input)
{
    input = input.replace('<', '&lt;');
    input = input.replace('>', '&gt;');
    return input;
}

But it doesn't seem to replace >, only <. Also tried like this:

input = input.replace('<', '&lt;').replace('>', '&gt;');

But I get the same result.

Can anyone point out what I'm doing wrong here? Cheers.

like image 697
VIVA LA NWO Avatar asked Dec 27 '25 16:12

VIVA LA NWO


1 Answers

A more robust way to do this is to create an HTML text node; that way all of the other potentially invalid content (there's more than just < and >) is converted. For example:

var message = document.getElementById('like').value;
document.getElementById('changer').appendChild(document.createTextNode(message));

UPDATE

You mentioned that your event was firing upon each key press. If that's what's triggering this code, you'll want to remove what was previously in the div before appending the text. An easy way to do that is like this:

var message = document.getElementById('like').value;
var changer = document.getElementById('changer');
changer.innerHTML = '';
changer.appendChild(document.createTextNode(message));
like image 123
Jacob Avatar answered Dec 31 '25 03:12

Jacob