12

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:

Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
Fifi
  • 3,360
  • 2
  • 27
  • 53
  • Possible duplicate of [JQuery Text Editor Paste Without Formatting](https://stackoverflow.com/questions/34497333/jquery-text-editor-paste-without-formatting) – prasanth Nov 07 '18 at 09:18
  • https://stackoverflow.com/questions/31822471/how-to-filter-user-pasted-content-in-contenteditable-div – Al.UrBasebelon Tomeh Nov 07 '18 at 09:19
  • 1
    This is not a duplicate of JQuery Text Editor Paste Without Formatting. Restrict paste is not the same as paste without formating – Fifi Nov 07 '18 at 09:24

1 Answers1

15

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>
mfluehr
  • 2,832
  • 2
  • 23
  • 31
  • Is there any way to make this work with both pasted text and text that was dragged and dropped into the contenteditable? – MikeMichaels Jul 22 '20 at 12:12
  • @MikeMichaels You could try listening to `input` events, when the `inputType` value is `'insertFromDrop'`. A full answer would merit its own SO question. – mfluehr Jul 23 '20 at 15:18