Remove all tags inside a contenteditable

Asked

Viewed 468 times

2

I want to prevent text formatting from on a website and for that I need to remove all tags (except <br>) that they had inside a text box, in case someone thinks of pasting some content from some other site.

An example not to get confused:

var text = "<b>Olá</b>, Usuário<br><i>Seja bem vindo</i>!"
removeHTML(text) = "Olá, Usuário<br>Seja bem vindo!"

2 answers

4


One solution is to use a regular expression to remove all HTML tags except the <br> or <br/>:

var texto = "<b>Olá</b>, Usuário<br><i>Seja bem vindo</i>!";

texto = texto.replace(/<(?!br\s*\/?)[^>]+>/g, '');

alert(texto); // Saída: Olá, Usuário<br>Seja bem vindo!

2

One way is:

1- break this by line breaks, getting an array of text pieces
2-then create a new widget and give that new widget as HTML each string
3- use the innerText of this element as the Browser does the work for us :)
4-re-merge the array by resetting the separator

You could do that with Regex but Browser is better than any Regex knowing what HTML tags are. Hence my suggestion to use an element (via Browser).

Example: http://jsfiddle.net/9rj59ocs/

var text = "<b>Olá</b>, Usuário<br><i>Seja bem vindo</i>!"

function removeHTML(str) {
    var partes = str.split(/<br\s?\/?>/);
    return partes.map(function (str) {
        var el = document.createElement('div');
        el.innerHTML = str;
        return el.innerText;
    }).join('<br />');
   }

alert(removeHTML(text));

  • 1

    Thank you! Never would I think of using innerText for this rsrs

  • Eita, had forgotten the <br/> tag that can be used too, but I think I can change your code.

  • @Iagobruno edited the answer to be more comprehensive in the tag <br />

Browser other questions tagged

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