如何获取包含 HTML 的字符串的字数?

How do I get the word count of a string that includes HTML?

我有一个呈现博客的 FreeMarker 模板 post。我想获取博客 post 的字数,以便我可以将其推送到 Google Tag Manager 进行分析。这里需要注意的是字数不能包括 HTML 个字符。

我结合了 word_list and size 内置函数,这让我很接近。

[#assign blogPost = "<h1>The Chihuahua</h1><p>The chihuahua ran across the road. Everyone thought it was a bad idea.</p><p>But he made it safely across.</p>"]

${blogPost?word_list?size}

但是,我需要在计算单词之前去掉HTML。

provides the final missing piece. Append the replace built-in 在 word_listsize 之前带有 "r" 标志 built-ins:

${blogPost?replace("<[^>]+>", "", "r")?word_list?size}