admin管理员组文章数量:1326332
I'm trying to convert characters like <
and >
into <
and >
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('<', '<');
input = input.replace('>', '>');
return input;
}
But it doesn't seem to replace >
, only <
. Also tried like this:
input = input.replace('<', '<').replace('>', '>');
But I get the same result.
Can anyone point out what I'm doing wrong here? Cheers.
I'm trying to convert characters like <
and >
into <
and >
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('<', '<');
input = input.replace('>', '>');
return input;
}
But it doesn't seem to replace >
, only <
. Also tried like this:
input = input.replace('<', '<').replace('>', '>');
But I get the same result.
Can anyone point out what I'm doing wrong here? Cheers.
Share Improve this question edited Jun 18, 2010 at 0:53 Marcel Korpel 21.8k6 gold badges62 silver badges80 bronze badges asked Jun 18, 2010 at 0:51 VIVA LA NWOVIVA LA NWO 3,9226 gold badges25 silver badges21 bronze badges2 Answers
Reset to default 6A 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));
Try something like this:
function convertHTML(input)
{
input = input.replace(/>/g, '>');
input = input.replace(/</g, '<');
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.
本文标签: Converting HTML to its safe entities with JavascriptStack Overflow
版权声明:本文标题:Converting HTML to its safe entities with Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742200458a2431863.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论