【问题标题】:YouTube videos API snippet title contains special characters in Next.jsYouTube 视频 API 片段标题包含 Next.js 中的特殊字符
【发布时间】:2020-06-25 08:47:55
【问题描述】:
我想获得不包含特殊字符的正确视频 sn-p 标题。
我正在使用 API:
https://www.googleapis.com/youtube/v3/search,
带有snippet的部分。
目前,我收到下面的snippet.title:
I'M GONNA CARRY HER!!! Fortnite With Karina!
我希望得到这个标题:
我要抱她!!!与卡琳娜的堡垒之夜!
【问题讨论】:
标签:
javascript
next.js
youtube-data-api
【解决方案2】:
我正在使用escape-goat,因为它可以作为独立函数或tagged template literal 运行,具体取决于您的用例:
const {htmlUnescape} = require('escape-goat');
htmlUnescape("I'M GONNA CARRY HER!!! Fortnite With Karina!");
//=> 'I'm gonna carry her!!! Fortnite With Karina!'
htmlUnescape`Title: ${"I'M GONNA CARRY HER!!! Fortnite With Karina!"}`;
//=> 'Title: I'm gonna carry her!!! Fortnite With Karina!'
在处理 html 编码/解码时,请始终警惕潜在的XSS exploitation。
【解决方案3】:
如果您想使用原始 JS 而不是导入库,我在旅行中看到了一些适用于您提出的简单用例的东西。它基本上是去除分隔符以获得表示 Unicode-16 字符的整数。 fromCharCode 查找该整数并返回与您提供的整数匹配的字符。
const unescape = (str) => {
return str.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
}
正如 Matt Hosch 在他的回答中提到的,您需要清理收到的任何数据以防止 XSS。