使用Javascript修剪并发送到剪贴板
我有下面的Javascript将div的内容复制到剪贴板 div的内容总是不同的,但是结果当前总是有大约5个空行,每个空行在结果之前都有一个空格。我无法更改此设置,因此我希望下面的函数在结果之前和之后修剪所有空白 我知道使用Javascript修剪并发送到剪贴板,javascript,copy,trim,Javascript,Copy,Trim,我有下面的Javascript将div的内容复制到剪贴板 div的内容总是不同的,但是结果当前总是有大约5个空行,每个空行在结果之前都有一个空格。我无法更改此设置,因此我希望下面的函数在结果之前和之后修剪所有空白 我知道 str.trim() 可能是最好的,但是作为一名javascript新手,我一直在努力将其插入下面的内容 <script> function copyToClipboard(element) { var $temp = $("<textarea>
str.trim()
可能是最好的,但是作为一名javascript新手,我一直在努力将其插入下面的内容
<script>
function copyToClipboard(element) {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val( $(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '')).select();
document.execCommand("copy");
$temp.remove();
}
功能copyToClipboard(元素){
变量$temp=$(“”);
var brRegex=//gi;
$(“正文”)。追加($temp);
$temp.val($(element.html().replace(brRegex,“\r\n”).replace(//g,”).select();
文件。执行命令(“副本”);
$temp.remove();
}
有人能帮忙吗
谢谢 您的代码片段非常适合我。但是,如果要在某个位置插入修剪,则应在此处:
function copyToClipboard(element) {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select();
document.execCommand("copy");
$temp.remove();
}
功能copyToClipboard(元素){
变量$temp=$(“”);
var brRegex=//gi;
$(“正文”)。追加($temp);
$temp.val($(element.html().replace(brRegex,“\r\n”).replace(//g,”).trim()).select();
文件。执行命令(“副本”);
$temp.remove();
}
解释是$(element).html()是一个字符串,是替换要替换的内容后要修剪的字符串
html的完整代码段:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Copy</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"
></script>
</head>
<body>
<div class="copy" contenteditable="true">HI<br />I am me! <span>I want to kill you!</span></div>
<button class="copy-button">copy</button>
<script>
function copyToClipboard(element) {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select();
document.execCommand("copy");
$temp.remove();
}
$('.copy-button').on('click', _ => {
copyToClipboard($('.copy'));
console.log("HI");
});
</script>
</body>
</html>
复制
嗨
我就是我!我想杀了你!
复制
功能copyToClipboard(元素){
变量$temp=$(“”);
var brRegex=//gi;
$(“正文”)。追加($temp);
$temp.val($(element.html().replace(brRegex,“\r\n”).replace(//g,”).trim()).select();
文件。执行命令(“副本”);
$temp.remove();
}
$('.copy button')。在('click',上{
copyToClipboard($('.copy'));
控制台日志(“HI”);
});