转义 HTML 个实体并动态呈现 URL

Escape HTML entities and render URL dynamically

问题可见here

我在前端使用 Sanity headless CMS 和 GatsbyJS 构建了一个站点。

我正在动态查询 URL,以便它可以在 </iframe>src 属性内呈现 问题是当用户添加 URL包含 &amp,对于 Google 日历的嵌入代码很常见。

&amp link 不再有效,日历中断(变为空白)。 除非我直接在src中硬编码,这正是我们想要避免的。

如何 mitigate/escape 这个问题并得到它,以便我可以相应地呈现 URL?

我研究了 encodeURIencodeURIComponent,甚至尝试了这个自定义函数:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

没有骰子...

我当前的实现

// sanity schema
export default {
  type: 'document',
  title: 'Google Calendar',
  name: 'calendar',
  fields: [
    {
      type: 'string',
      name: 'Title',
    },
    {
      type: 'url',
      name: 'URL',
      validation: (Rule) => Rule.required(),
    },
  ],
};

//gastby 
export default function GoogleCalendar() {
  const { calendar } = useStaticQuery(graphql`
    query {
      calendar: allSanityCalendar {
        nodes {
          URL
          Title
        }
      }
    }
  `);

  if (!calendar.nodes.length) return null;
  return (
    <>
      <div>
        {calendar.nodes.map((node) => (
          <iframe
            src={node.URL}
            id="test"
            title={node.Title}
            width="100%"
            height="1000px"
            async
          />
        ))}
      </div>
    </>
  );
}

这是一个说明问题的沙箱: https://stackblitz.com/edit/iframe-dynamic-src

这里您的沙箱正在运行:https://iframe-dynamic-src-pmxqbb.stackblitz.io

我已通过以下方式修复它:

  <iframe
    src={decodeURIComponent(
      encodeURIComponent(brokeUrl.replace(/&amp;/g, "&"))
    )}
    width="800"
    height="600"
    frameborder="0"
    scrolling="no"
    content
  />

Decoding an encoded URL 用 &.

全局替换符号 (&amp;)