在Google Apps脚本中使用html编码时遇到问题 [英] Trouble with html encoding in Google Apps Script

查看:78
本文介绍了在Google Apps脚本中使用html编码时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将HTML实体字符转换为其unicode版本。例如,当我有& amp 时,我只需要& 。是否有一个特殊的功能,或者我必须使用函数 replace()为每对 HTML实体字符< - > Unicode字符



预先感谢。

解决方案

即使Apps脚本中没有DOM,也可以解析出HTML并以这种方式获取纯文本:

  function getTextFromHtml(html){
return getTextFromNode(Xml.parse(html,true).getElement());

$ b $ function getTextFromNode(x){
switch(x.toString()){
case'XmlText':return x.toXmlString();
case'XmlElement':return x.getNodes()。map(getTextFromNode).join('');
default:return'';


$ / code $ / pre
$ b $ p

  getTextFromHtml(hello< div> foo< / div>& world< / div>< div>< / div> ;!) ; 

将会返回



hello foo&世界吧!。

为了说明,第二个参数为true的Xml.parse将文档解析为HTML页面。然后我们遍历文档(将修补缺失的HTML和BODY元素等,并转换为有效的XHTML页面),将文本节点转换为文本并展开所有其他节点。


I need to convert the HTML entity characters to their unicode versions. For example, when I have &amp, I would like just &. Is there a special function for this or do I have to use the function replace() for each couple of HTML Entity character <--> Unicode character?

Thanks in advance.

解决方案

Even though there's no DOM in Apps Script, you can parse out HTML and get the plain text this way:

function getTextFromHtml(html) {
  return getTextFromNode(Xml.parse(html, true).getElement());
}

function getTextFromNode(x) {
  switch(x.toString()) {
    case 'XmlText': return x.toXmlString();
    case 'XmlElement': return x.getNodes().map(getTextFromNode).join('');
    default: return '';
  }
}

calling

getTextFromHtml("hello <div>foo</div>&amp; world <br /><div>bar</div>!");

will return

"hello foo& world bar!".

To explain, Xml.parse with the second param as "true" parses the document as an HTML page. We then walk the document (which will be patched up with missing HTML and BODY elements, etc. and turned into a valid XHTML page), turning text nodes into text and expanding all other nodes.

这篇关于在Google Apps脚本中使用html编码时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆