Reputation:
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);
});
Upvotes: 1
Views: 1456
Reputation: 824
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();
});
Upvotes: 2
Reputation: 1504
You need to create an element first in order to change attributes.
otherwise you'll have to do string manipulation, either using loops or Regex.
let htmlAsText = `<p style="font:10pt Times New Roman, Times" pid="123">
This Amendment contains only the Cover Page, this Explanatory Note.
</p>`;
let div = document.createElement("div");
div.innerHTML = htmlAsText;
div.querySelector("p").removeAttribute("pid");
document.querySelector("body").appendChild(div)
createElement() removeAttribute()
Upvotes: 1