A maneira como eu faço isso é praticamente uma linha única.
A função cria um objeto Range e, em seguida, cria um DocumentFragment no Range com a string como conteúdo filho.
Em seguida, ele captura o texto do fragmento, remove quaisquer caracteres "invisíveis" / de largura zero e remove qualquer espaço em branco à esquerda / à direita.
Sei que essa questão é antiga, só pensei que minha solução fosse única e queria compartilhar. :)
function getTextFromString(htmlString) {
return document
.createRange()
// Creates a fragment and turns the supplied string into HTML nodes
.createContextualFragment(htmlString)
// Gets the text from the fragment
.textContent
// Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
.replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
// Trims off any extra space on either end of the string
.trim();
}
var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');
alert(cleanString);