Converting HTML to its safe entities with Javascript

Posted by James P on Stack Overflow See other posts from Stack Overflow or by James P
Published on 2010-06-18T00:51:26Z Indexed on 2010/06/18 1:03 UTC
Read the original article Hit count: 446

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html