首页 文章

替换“ “使用常用方法在JavaScript Azure功能中不起作用

提问于
浏览
1

目标

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

设置

发生事件时会触发Telligent webhook . Azure Logic应用程序接收事件JSON . JSON值是HTML格式 . Azure Logic App管道内的JavaScript Azure功能将JSON值转换为纯文本 . 管道中的最后一步发布了Slack中的纯文本 .

Azure函数的传入代码示例

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

转换方法

这是Azure功能中的基本代码 . 我遗漏了与此问题无关的部分,但如果有必要,可以提供整个脚本 .

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,因为我不是程序员,我正在寻求简化我的工作流程 . 但是我很感激有关代码或我的整个方法的任何建议 .

1 回答

  • 2

    通常,您不希望尝试使用正则表达式或字符串替换来解析HTML . 有太多事情可能会出错 . See this now famous StackOverflow answer.(甚至made into a T-Shirt . )

    相反,您应该使用专门为此目的而构建的技术 . 如果您使用的是Web浏览器,则可以使用this question的答案中描述的技术 . 但在Azure Functions中,您的JavaScript不在浏览器中运行,而是在Node JS环境中运行 . 因此,您需要使用诸如Cheeriohtmlparser2(和其他)之类的库 .

    以下是使用Cheerio的示例:

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

    另外,关于这部分:

    ...因为我不是程序员......

    是的,你是 . 你现在正在编程 . 编写代码的任何人都是程序员 . 没有俱乐部或秘密握手 . 我们都是这样开始的 . 干得好问题,祝你旅途愉快!

相关问题