使用常用方法将“替换为”在 JavaScript Azure 函数中不起作用

Replacing " with " using common methods does not work in a JavaScript Azure Function

目标

将从 Telligent(一个外联网平台)提取的 HTML 转换为纯文本并发送到 Slack

设置

Telligent webhook 在事件发生时被触发。 Azure 逻辑应用程序接收到事件 JSON。 JSON 值在 HTML 中。 Azure 逻辑应用程序管道内的 JavaScript Azure 函数将 JSON 值转换为纯文本。管道中的最后一步在 Slack 中发布纯文本。

Azure 函数的传入代码示例

"body": "<p>&quot; &#39;</p><div style=\"clear:both;\"></div>"

变换方法

这是Azure Functions中的基本代码。我省略了与这个问题似乎无关的部分,但如果需要可以提供整个脚本。

module.exports = function (context, data) {
   var html = data.body;

// Change HTML to plain text
   var text = JSON.stringify(html.body);
   var noHtml = text.replace(/<(?:.|\n)*?>/gm, '');
   var noHtmlEncodeSingleQuote = noHtml.replace(/&#39;/g, "'");
   var noHtmlEncodeDoubleQuote = noHtmlEncodeSingleQuote.replace(/&quot;/g, "REPLACEMENT");

// Compile body for Slack
   var readyString = "Slack text: " + noHtmlEncodeDoubleQuote;

// Response of the function to be used later
   context.res = {
     body: readyString
   };

   context.done();
};

结果

在Slack中发布时,单引号替换成功并准确解析。

以下双引号替换方法在 Azure 函数中引发 Status: 500 Internal Server Error

不成功的替换方法

"\""
'"'
&quot;
"'"'"
"["]"
"(")"

将这些替换方法放在它们自己的 var 中也会引发相同的错误。例如:

var replace = "\""
...
var noHtmlEncodeDoubleQuote = noHtmlEncodeSingleQuote.replace(/&quot;/g, replace);

代码似乎是正确的,因为当我用 abc 替换 &quot; 时,替换成功。

谢谢

请原谅我的 JavaScript,因为我不是程序员并且正在寻求简化我的工作流程。但是,我非常感谢有关代码或我的整个方法的任何建议。

通常,您不想尝试使用正则表达式或字符串替换来解析 HTML。可能出错的事情太多了。 See this now famous Whosebug answer. (It was even made into a T-Shirt.)

相反,您应该使用专门为此目的构建的技术。如果您使用的是 Web 浏览器,则可以使用 this question. But in Azure Functions, your JavaScript doesn't run in a browser, it runs in a Node JS environment. Therefore, you need will need to use a library such as Cheerio or htmlparser2(及其他)的答案中描述的技术。

这是一个使用 Cheerio 的例子:

var cheerio = require('cheerio');
var text = cheerio.load(html.body).text();

另外,关于这部分:

... as I am not a programmer ...

是的,你是。您现在显然正在编程。任何编写代码的人都是程序员。没有俱乐部或秘密握手。我们都是这样开始的。提问得真好,祝你一路顺风!