Remove HTML tags in <input> on keypress

2019-08-31 00:20发布

I made a code and it's working fine to remove HTML tags in <input> by jQuery

$("input").on("keypress",function(e){
    var val = $(this).val();
    var open = val.indexOf('<');
    var close = val.indexOf('>');
    if(open!==-1 && close!==-1) {
      $(this).val(val.replace(val.slice(open,close+1),""));
    }
});

Demo : http://jsbin.com/uzibey/1/edit

But any better idea or functions should I use ?

PS : No server side security needed , Using in Admin area btw.

4条回答
2楼-- · 2019-08-31 00:25

Try this

$("input").on("keypress",function(e){
    var val = $(this).val();
    var regex = /(<([^>]+)>)/ig;
    var result = val .replace(regex, "");
    $(this).val(result);

});
查看更多
欢心
3楼-- · 2019-08-31 00:32

You can also use the DOM to sanitise your input. Simply create a dummy element (without inserting it into the document) and insert the value of the input using innerHTML. Then remove all nodes except text nodes.

This has the benefit of using an actual HTML parser to detect HTML, instead of a regex approximation. Anything that can be interpreted as an HTML element by the browser will be removed.

Here is a very basic demonstration: http://jsfiddle.net/uA94h/

EDIT: The above demonstration removes non-text nodes entirely. By request, here is a demonstration where elements are replaced with their text: http://jsfiddle.net/TknBs/.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-08-31 00:41

you can use regex for this

<[^>]*(>|$)

try applying this one to the input string to see if it helps...

查看更多
你好瞎i
5楼-- · 2019-08-31 00:50

I found 2 ways:

One is here on stackoverflow

The other one is this:

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
查看更多
登录 后发表回答