在输入框中禁用一些html输出

我有一个像聊天框一样的输入。 (用户在输入中键入内容并在页面上输出)。 我只是注意到用户也可以在输入框中使用html标签来更改输出。

示例:如果我键入Hello ,输出文本将以粗体显示,依此类推……

我不想完全禁用这个function。 但是有些标签我不想输出(例如h1h2 ……)。 我认为这是可能的正则表达式(不知道如何继续这样做),但我觉得可能有一个更容易的解决方案,如果没有,只要投入任何工作。

下面的代码是我的输入框工作的原因:

 $('form').on('submit', function(e){ e.preventDefault(); checkValue(); }); function checkValue() { var message = document.getElementById("userinput").value; $('#output').html(message); } 

谢谢。

看看是否符合您的需求:

 var message = $('
', { html: document.getElementById("userinput").value }).find(':header').remove().end().html();

或者您可以使用例如replaceWith(function(){return ''+this.innerHTML+'';})而不是remove()

DEMO jsFiddle

您需要在checkValue函数中添加另一个部分:

 function checkValue() { var text = document.getElementById("userinput").value; var message = text.replace(/

/g,"<h1>"); $('#output').html(message); }

看看我如何用转义字符和文本(h1)替换所有h1元素。

这应该工作,你可以一次又一次地重复它,以摆脱你不想要的一切,例如

 function checkValue() { var text = document.getElementById("userinput").value; var check = text.replace(/

/g,"<h1>"); var check2 = check.replace(/

/g,"<h2>"); var message = check2.replace(//g,"<table>") $('#output').html(message); }

替换function还有更多内容: http : //www.w3schools.com/jsref/jsref_replace.asp

以下是我在此网站上发现的另一种方式:

如何从字符串中删除某些html标签?