在contenteditable中限制粘贴(HTML / JS)

问题描述 投票:6回答:1

我想阻止用户在contenteditable div中粘贴不允许的标记。

我想将粘贴限制为粗体,斜体,打击,下划线和链接。

什么是最好的方式(我使用jQuery)?

这不是JQuery Text Editor Paste Without Formatting的副本。我不想在没有格式化的情况下粘贴。我想选择/限制一些标记。

我已经阅读了以下问题,没有提供明确答案:

javascript jquery html contenteditable
1个回答
5
投票

通过聆听可编辑元素的paste事件来限制粘贴的内容。在此事件中,您可以使用正则表达式过滤用户尝试粘贴的数据。

const el = document.querySelector('p');

el.addEventListener('paste', (e) => {
  // Get user's pasted data
  let data = e.clipboardData.getData('text/html') ||
      e.clipboardData.getData('text/plain');
  
  // Filter out everything except simple text and allowable HTML elements
  let regex = /<(?!(\/\s*)?(a|b|i|em|s|strong|u)[>,\s])([^>])*>/g;
  data = data.replace(regex, '');
  
  // Insert the filtered content
  document.execCommand('insertHTML', false, data);

  // Prevent the standard paste behavior
  e.preventDefault();
});
<p contenteditable>Try pasting content into this paragraph. The pasted content can include a <b>BOLD</b>, <i>ITALIC</i>, <s>STRIKE</s>, or <u>UNDERLINE</u>. It can also include a <a href='#'>LINK</a>.</p>
© www.soinside.com 2019 - 2024. All rights reserved.