I have an input that works like a chat box. (The user types something in the input and it outputs on the page). I just noticed that the user can also use html tags in my input box to change the output.
Example: If I typed <b>Hello</b>
, the output text would be bolded and so on...
I don't want to disable this function completly. But there are some tags that I don't want outputted (example h1 or h2...). I think that's it's possible with regex (not sure how too proceed with that though), but I feel like there may be a easier solution, if not, just throw in whatever works.
The code below is what gets my input box to work:
$('form').on('submit', function(e){
e.preventDefault();
checkValue();
});
function checkValue() {
var message = document.getElementById("userinput").value;
$('#output').html(message);
}
Thanks.
See if that fits your needs:
var message = $('<div/>', {
html: document.getElementById("userinput").value
}).find(':header').remove().end().html();
Or you could use e.g replaceWith(function(){return '<h>'+this.innerHTML+'</h>';})
instead of remove()
.
DEMO jsFiddle
You need to add another part to your checkValue function:
function checkValue() {
var text = document.getElementById("userinput").value;
var message = text.replace(/<h1>/g,"<h1>");
$('#output').html(message);
}
See how I have replaced all h1 elements with escaped characters and the text (h1).
This should work and you can repeat it again and again to get rid of everything you don't want, e.g.
function checkValue() {
var text = document.getElementById("userinput").value;
var check = text.replace(/<h1>/g,"<h1>");
var check2 = check.replace(/<h2>/g,"<h2>");
var message = check2.replace(/<table>/g,"<table>")
$('#output').html(message);
}
There is more on the replace function here: http://www.w3schools.com/jsref/jsref_replace.asp
Here is a different way that I found on this site:
How can I strip certain html tags out of a string?