Remove tags JQUERY

2

I need to remove the HTML tags from a variable, or do not interpret the HTML of this variable. The problem is that the variable has its value coming from an input, so:

var msg = $('input').val();

As there is no way to get the .text () from the input, I do not know how to remove or at least not interpret the HTML tags there! Any help?

    
asked by anonymous 01.07.2018 / 01:58

3 answers

2

If you want to keep the tags unread, you can replace < and > with your HTML entity &lt; and &gt; respectively. The result the browser will interpret as a common text:

var msg = $('input').val();
msg = msg.replace(/</g, '&lt;').replace(/>/g, '&gt;');
$("body").append(msg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputvalue="<b>abc</b>">

Removing tags with .replace and regular expression

var msg = $('input').val();
msg = msg.replace(/<.+?>/g, '');
console.log(msg)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputvalue="<i class='classe'>abc1</i> <b>def2</b>">

The expression <.+?> captures everything that is <nome da tag, atributos, fechamento etc.> and .replace removes the string.

    
01.07.2018 / 02:17
1

When we put a string in html format inside a jquery $ () selector, jquery turns that string into an object that can be manipulated by jquery itself, and then you can extract the text.

var msg = $('input').val(); // output -> <div>Ola</div>
var textoExtraido = $(msg).text() == "" ? msg : $(msg).text(); // output -> Ola

Example: link

    
01.07.2018 / 02:03
1

Since you're using jQuery, you can treat the field like this:

var msg = $('input').val();

//retira as tags
$('<p/>').html(msg).text();

//faz encode das tags
$('<p/>').text(msg).html();

Here's an example:

function f() {

var msg = $('input').val();

var opcao1 = $('<p/>').html(msg).text();

var opcao2 = $('<p/>').text(msg).html();

$('input[name="opcao1"]').val(opcao1);

$('input[name="opcao2"]').val(opcao2);

};

$('input').keyup(function() { f(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputplaceholder="Digite o texto" type="text" /><br />
<p>Opção 1 (removendo tags)</p>
<input name="opcao1" type="text" />
<p>Opção 2 (encode tags)</p>
<input name="opcao2" type="text" />
    
01.07.2018 / 15:15