How to convert html string to plain text without html tags in google app script?

I’m new to google app script.

I was trying to convert html string to plain text without html tags in google app script using the reference in this question.

However, when I try to apply it to my script, it is not working as expected.

This is the script that I use:

function toStringFromHtml(html)
{
  
html = '<div>' + html + '</div>';
html = html.replace(/<br>/g,"");
var document = XmlService.parse(html);
var strText = XmlService.getPrettyFormat().format(document);
strText = strText.replace(/<[^>]*>/g,"");
return strText;
}

and this is the output: enter image description here

While my actual expectation is in the third column.

Can someone tell me what is wrong with my previous script?

Thank you!

Answer

In your situation, for example, how about the following modification?

From:

return strText;

To:

return strText.trim();

Reference: