Код, который я создаю, заключается в копировании выделенного текста без касания клавиатуры или щелчка правой кнопкой мыши по тексту. Хотя я все еще хочу удалить пробелы или новые строки после того, как они были выбраны с помощью регулярного выражения. Хотя я не уверен, почему это не работает. Любая помощь?
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>
Согласно этому документ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>