Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting partial text when copying and modifying a text

I have an react application and what I’m trying to accomplish here is to copy a text from the html and modifying it before send it back to the user. So far I have accomplished it, but even if I select a part of the text, I always receive the complete text from the table cell below. Is it possible to return only the selected text?

<table oncopy={handleCopy}>
   <thead></thead>
   <tbody>
      <tr>
         <td>12-23</td>
      </tr>
   </tbody>
</table>
const handleCopy = (e) => {
    const text = document.getSelection().anchorNode.textContent
    e.preventDefault()
    e.clipboardData.setData('text/plain', formatString(text))
}

When I select the value 12-23, it should return 1223, and it’s working, but when I select the partial value 12-2 and try to copied it, it keeps me returning 1223 and not 122.

I see that anchorNode has two properties, textContent and wholeText, but both has the same value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your code, you get the anchor node from the selection and then return the content of the node, not the content of the selection.

I think

const text = document.getSelection().toString()  

should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading