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

Fif*_*ifi 7 html javascript jquery contenteditable

我想阻止用户在contenteditablediv中粘贴不允许的标记.

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

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

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

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

mfl*_*ehr 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();
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)