繁体   English   中英

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

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

目标

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

设定

事件发生时将触发智能Webhook。 Azure逻辑应用程序接收事件JSON。 JSON值为HTML。 Azure Logic应用程序管道中的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中发布时可以准确解析。

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

替换方法不成功

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

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

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

该代码似乎是正确的,因为当我替换&quot; 使用类似abc东西,替换成功。

谢谢

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

通常,您不想尝试使用正则表达式或字符串替换来解析HTML。 有太多事情可能出错。 看到这个现在著名的StackOverflow答案。 (它甚至被制成了T恤 。)

相反,您应该使用为此目的而专门构建的技术。 如果您使用的是网络浏览器,则可以使用此问题的答案中所述的技术。 但是在Azure Functions中,您的JavaScript不在浏览器中运行,而是在Node JS环境中运行。 因此,你需要将需要使用一个库如Cheeriohtmlparser2 (及其他)。

这是使用Cheerio的示例:

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

另外,关于这部分:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM