Home > Back-end >  Getting partial text when copying and modifying a text
Getting partial text when copying and modifying a text

Time:06-22

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.

CodePudding user response:

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.

  • Related