If you want to keep tags without them being interpreted, you can replace the <
and the >
by its HTML entity <
and >
respectively. The result the browser will interpret as a common text:
var msg = $('input').val();
msg = msg.replace(/</g, '<').replace(/>/g, '>');
$("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.
Thanks. I didn’t know that one.
– Vitor Leite
But like, it’s not required to have HTML in this val(), so it’ll be a mistake?
– Vitor Leite
I made an adjustment in the code, if there is no html it takes the normal content. No error no
– Joao Paulo