0

I can copy a string into the clipboard using code below:

function copyText(text) {

  if (navigator.clipboard) { // default: modern asynchronous API
    return navigator.clipboard.writeText(text);
  } else if (window.clipboardData && window.clipboardData.setData) {     // for IE11
    window.clipboardData.setData('Text', text);
    return Promise.resolve();
  } else {
    // workaround: create dummy input
    const input = h('input', { type: 'text' });
    input.value = text;
    document.body.append(input);
    input.focus();
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }
}

The issue is I want to copy a representation of an array (actually an array of arrays).

So far when I give the function an array it just copy the elements and separate them with a semi colon!

How can I copy an array of arrays into clipboard using javascript?

1 Answer 1

1

You can keep your function, just use JSON.stringify and JSON.parse.

const arr = [[1,2],[1,2]];
copyText(JSON.stringify(arr));
// then wherever you have them pasting
JSON.parse(pastedText);

Full Example:

function copyText(text) {
  if (navigator.clipboard) { // default: modern asynchronous API
    return navigator.clipboard.writeText(text);
  } else if (window.clipboardData && window.clipboardData.setData) {     // for IE11
    window.clipboardData.setData('Text', text);
    return Promise.resolve();
  } else {
    // workaround: create dummy input
    const input = h('input', { type: 'text' });
    input.value = text;
    document.body.append(input);
    input.focus();
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }
}



click.onclick = ()=>{
const arr = [[1,2],[1,2]];
copyText(JSON.stringify(arr));
}
<input placeholder="Paste Here!">
<button id="click">Click to copy!</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.