gpt4 book ai didi

javascript - 如何.trim() 选定的文本?

转载 作者:行者123 更新时间:2023-11-29 23:30:31 24 4
gpt4 key购买 nike

这可能是一个非常简单的问题,但我似乎无法以某种方式解决它。

我希望能够从表格的 td 元素中选择文本。问题是文本中有一个选项卡我想去掉。

到目前为止我试过这个:

function getSelectionText(){
var selectedText = ""
if (window.getSelection){ // all modern browsers and IE9+
selectedText = window.getSelection().toString().trim()
}
return selectedText
}

$('td').click(function(){
var selected = getSelectionText();
document.execCommand('copy');
});

遗憾的是,这仍然返回复制的文本,后面有一个制表符。尝试将密码复制到密码字段时,这真的很烦人,因为用户看不到带点的密码中有一个制表符。

希望有人能提供帮助,在此先感谢!

编辑:

我稍微更改了已接受的答案,不再需要 getSelectionText() 函数。希望这对遇到同样问题的人有所帮助。

$('td').click(function(){
var selected = $(this).html();
var inp = $("<input/>",{id:"copySelected"});
$("body").append(inp)
inp.val(selected);
inp[0].select();
document.execCommand('copy');
inp.remove();
});

每次点击都会将点击的td-cell复制到剪贴板

最佳答案

你有 jQuery,所以使用 $.trim()

$.trim(window.getSelection().toString())

它应该适用于您使用的 jQuery 版本支持的所有浏览器。

$.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

但是:execCommand 副本采用选定 字符串而不是您复制和更改的字符串。

在复制之前,您需要更改所选范围或将操作的字符串复制到其他地方。

在这里,我创建了一个临时字段来在复制之前保存被操作的字符串。

function getSelectionText(){
var selectedText = ""
if (window.getSelection){ // all modern browsers and IE9+
selectedText = $.trim(window.getSelection().toString());
}
return selectedText;
}

$('td').click(function(){
var selected = getSelectionText();
console.log(selected.length,selected,encodeURIComponent(selected))
var inp = $("<input />",{id:"copySelected"});
$("body").append(inp)
inp.val(selected);
inp[0].select();
document.execCommand('copy');
inp.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table><tbody><tr><td>Here is some text with trailing tabs </td><td>|Next cell</td></tr>
</table>
<textarea>Paste the 36 chars (47 with tabs) in after clicking</textarea>

关于javascript - 如何.trim() 选定的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com