Remove JQUERY tags

Asked

Viewed 518 times

2

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

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

Since there is no way to get the . text() input, I don’t know how to remove or at least not interpret the HTML tags there! Some help ?

3 answers

2


If you want to keep tags without them being interpreted, you can replace the < and the > by its 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>
<input value="<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>
<input value="<i class='classe'>abc1</i> <b>def2</b>">

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

1

When we place 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: https://jsfiddle.net/ag1swze4/4/

  • Thanks. I didn’t know that one.

  • But like, it’s not required to have HTML in this val(), so it’ll be a mistake?

  • 1

    I made an adjustment in the code, if there is no html it takes the normal content. No error no

1

As you are 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();

Following 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>

<input placeholder="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" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.