Convert HTML to its safe objects using Javascript

I'm trying to convert a character type <and >in &lt;and &gt;etc.

User input is taken from the text field and then copied to the DIV under the name changer.

here is 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 he does not replace >, only <. Also tried like this:

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

But I get the same result.

Can someone point out what I'm doing wrong here? Greetings.

+3
source share
2 answers

- HTML node; ( , < > ). :

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

UPDATE

, . , , div, . :

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

- :

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

  return input;
}

> < , < > , g .

+1

Source: https://habr.com/ru/post/1750605/


All Articles