Clear Html Tags from an input result, with the exception

Asked

Viewed 113 times

1

How do I remove all html tags from a string with exception? Ex:

var exemplo = "<div><p>Leno<span> Sousa</span> <i></i>var exemplo = "<div><p>Leno<span> Sousa</span></p></div>";var exemplo = "<div><p>Leno<span> Sousa</span></p></div>";></div>";

and return as:

var exemplo = "<p>Leno Sousa</p>";

as you can see cleared the tags and was only the tag 'p'.

1 answer

1


You can use a regex with .replace that removes all tags (pure Javascript).

I created a function that takes two parameters: the string and the tag that will be left, and returns only the text within the specified tag:

function removeTags(string, excecao){
   return excecao + string.replace(/(<([^>]+)>)/g, "").trim() + excecao.replace("<", "</");
}

var exemplo = "<div><p>Leno<span> Sousa</span> <i></i>";

var filtrado = removeTags(exemplo, "<p>");
console.log(filtrado);

Browser other questions tagged

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