views:

146

answers:

2

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.

+4  A: 

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));
Jacob
So all the HTML in the text node is safe? As in all the < and > and junk is converted to their entities?
VIVA LA NWO
I ran into a problem, the `updateChanger()` function is called on keyUp, so it's constantly making a new text node when I type into the text field. Should I just create the text node on document.ready instead?
VIVA LA NWO
Yes, it will treat your text as text rather than as markup, so it's equivalent to converting all the special characters.
Jacob
As for your event firing, you can always clear the `div` first.
Jacob
A: 

Try something like this:

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

  return input;
}

replace only replaces the first occurrence of > or < in the string, in order to replace all occurrences of < or >, use regular expressions with the g param to ensure the entire string is searched for all occurrences of the values.

Bug Magnet
You probably want to `return` the new value of `input`.
Marcel Korpel
This solves my problem thanks, but Jacob's answer is a better way to do what I'm doing so I'll be accepting his. Thanks a lot though! :)
VIVA LA NWO
No worries, I prefer Jacob's answer too and voted him up!
Bug Magnet