Search code examples
javascriptevent-handlingdom-eventsclipboardcopy-paste

Remove certain text before pasting it


I have a paste event where i get certain plain text, so i want to remove a text from the copied text and paste it.

text copied in Clipboard

<p style="font:10pt Times New Roman, Times;" pid="123">
    This Amendment contains only the Cover Page, this Explanatory Note.
</p>

So i want to remove is pid="123" , how can i possibly be able to do it?

    myTextArea.addEventListener('paste', (e) => {
     let html = e.clipboardData.getData('text/plain');
                
     console.log('i pasted', html);
    });

Solution

  • You can use regex pattern and replace method to get the correct string. Here is the code:

    myTextArea.addEventListener('paste', (e) => {
     let html = e.clipboardData.getData('text/plain');
     let transformed_html = html.replace(/pid=\"[0-9]*\"/, "");
     console.log('i pasted', transformed_html);
     
     const selection = window.getSelection();
     if (!selection.rangeCount) return false;
     selection.deleteFromDocument();
     selection.getRangeAt(0).insertNode(document.createTextNode(transformed_html));
    
     event.preventDefault();
    });