Remove all tags within a contenteditable

2

I want to prevent the formatting of text from a website and for this I need to remove all tags (except <br> ) inside a text box if someone thinks of pasting some content from some other site

An example to not be confused:

var text = "<b>Olá</b>, Usuário<br><i>Seja bem vindo</i>!"
removeHTML(text) = "Olá, Usuário<br>Seja bem vindo!"
    
asked by anonymous 21.12.2014 / 22:18

2 answers

4

One solution is to use a regular expression to remove all HTML tags except <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!
    
21.12.2014 / 22:44
2

One way is:

1- Break this down by line breaks, getting an array of pieces of text
2 - then create a new element and give that new element as HTML every string
3- use the innerText of this element because so the Browser does the work for us :)
4 - rejoin array by resetting tab

You could do this with RegEx but the Browser is better than any RegEx to know what HTML tags are. Hence my suggestion of using an element (via Browser).

Example: link

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));
    
21.12.2014 / 22:37