Remove HTML tags in <input> on keypress

2019-08-31 00:43发布

问题:

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.

回答1:

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/.



回答2:

Try this

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

});


回答3:

you can use regex for this

<[^>]*(>|$)

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



回答4:

I found 2 ways:

One is here on stackoverflow

The other one is this:

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");