10
votes

I would like to prevent the user from pasting non allowed markup in a contenteditable div.

I would like to restrict paste to bold, italic, strike, underline and links.

What is the best way (I'm using jQuery) ?

This is not a duplicate of JQuery Text Editor Paste Without Formatting. I don't want to paste without formatting. I want to select / restrict to some markups.

I already read the following questions, none provides a clear answer:

1
This is not a duplicate of JQuery Text Editor Paste Without Formatting. Restrict paste is not the same as paste without formatingFifi

1 Answers

12
votes

Restrict pasted content by listening to the editable element's paste event. Inside this event, you can filter the data the user is attempting to paste by using a regular expression.

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>