12

I have string variable with HTML entities:

var str = 'Some text & text';

I want to convert (decode) it to original characters:

Some text & text.

JavaScript doesn't have built-in function to achieve wanted result. I can't use jQuery or DOM objects because I need it to work in Google Apps Script.

How can I do that in simple way?

rik
  • 491
  • 3
  • 10

2 Answers2

21

You can use built-in Xml Services (reference):

var str = 'Some text & text';
var decode = XmlService.parse('<d>' + str + '</d>');
var strDecoded = decode.getRootElement().getText();

or you can use built-in E4X XML class.

var str = 'Some text &#x26; text';
var decode = new XML('<d>' + str + '</d>');
var strDecoded = decode.toString();
rik
  • 491
  • 3
  • 10
  • thanks for sharing this awesome hack! :) is there a way to go the other i.e. convert special characters in a string to their corresponding html entities? Thanks! :) – Saqib Ali Jan 03 '13 at 02:29
  • 1
    @Hafez `Xml.parse` has been replaced with [`XmlService.parse`](https://developers.google.com/apps-script/reference/xml-service/xml-service#parse(String)). –  Nov 30 '16 at 16:03
0

First you need to create a temporary Google Doc and get its docid

Then you need to enable the Drive API Advanced Service

Then you use the following code:

function htmltotext() {
  
  var html = 'Your <b>HTML</b> code &#x26; entities';
  var blob = HtmlService.createHtmlOutput(html).getBlob();

  var docid = 'Your doc id here';

  Drive.Files.update('',docid,blob);

  var doc = DocumentApp.openById(docid);
  var text = doc.getBody().getText();
  doc.saveAndClose();

  Logger.log(text);
  return text;
}
vstepaniuk
  • 667
  • 6
  • 14