Remove html tag but keep <br> Javascript

Asked

Viewed 322 times

2

I’m having doubts about how to remove html tags, but keep only <br>
This code removes the tags, but I would like to keep the <br> and maybe other tags.

function removeHtmlTag(strx,chop){ 
    if(strx.indexOf("<")!=-1)
    {
        var s = strx.split("<"); 
        for(var i=0;i<s.length;i++){ 
            if(s[i].indexOf(">")!=-1){ 
                s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length); 
            } 
        } 
        strx =  s.join(""); 
    }
    chop = (chop < strx.length-1) ? chop : strx.length-2; 
    while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; 
    strx = strx.substring(0,chop-1); 
    return strx+'...'; 
}

1 answer

3


If your code already removes all html tags currently, you can, before passing your function, replace all the <br> by a string specific, such as for example ~br~ and after going through its function, turn again all the strings ~br~ by a tag <br>

function trocarTexto() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("original", "modificado");
    document.getElementById("demo").innerHTML = res;
}
<html>
<body>

<p>Clique no botão para trocar o texto exemplo:</p>

<p id="demo">Texto original!</p>

<button onclick="trocarTexto()">Clique aqui</button>

</body>
</html>

  • I’m still learning javascript, could you give me an example of how to do this?

  • @jonyboy I added the example in the reply.

Browser other questions tagged

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