Как удалить «document.execCommand (« copy »)» пробелы и символы новой строки? - PullRequest
0 голосов
/ 02 мая 2018

Код, который я создаю, состоит в том, чтобы скопировать выделенный текст, не касаясь клавиатуры и не щелкая правой кнопкой мыши по тексту. Хотя я все еще хочу удалить пробелы или новые строки после того, как они были выбраны с помощью регулярных выражений. Хотя я не уверен, почему это не работает. Любая помощь?

Javascript

var t = "";
function gText(e) {
  t = document.all
    ?document.selection.createRange().text
    : document.getSelection();
 document.execCommand("copy").value = t.replace(/\s+/g, '');
}

document.onmouseup = gText;
if (!document.all) document.captureEvents(Event.MOUSEUP);

Html

<p> Some of the text</p>

<p> <b>Some</b> of the text</p>
<p> <b>Some</b> of the text</p>

<table><tr><td>wew</td></tr></table>

1 Ответ

0 голосов
/ 02 мая 2018

Согласно этому документу getSelection при приведении к строке возвращается выбранный текст.

Так что нужно использовать toString() или добавить пару кавычек, чтобы получить выделенный текст

var t = "";

function gText(e) {
  t = document.all ?
    document.selection.createRange().text :
    document.getSelection().toString();
  document.execCommand("copy").value = t.replace(/\s+/g, '');
  // for test only 
  document.getElementById("test").innerHTML = t.replace(/\s+/g, '');
}

document.onmouseup = gText;
if (!document.all) document.captureEvents(Event.MOUSEUP);
<p> Some of the text</p>

<p> <b>Some</b> of the text</p>
<p> <b>Some</b> of the text</p>

<table>
  <tr>
    <td>wew</td>
  </tr>
</table>
<!-- test DOM -->
<div id="test"></div>
...