Javascript copy to clipboard including html formatted text

最后都变了- 提交于 2019-12-12 04:09:48

问题


I'm relatively new to js so would like some help,

I've got a form which is generated in php. I want the user to be able to click a button and copy the flight results to the clipboard,

I have the following javascript function:

<script>

function copyToClipboard(element) {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(element).html().replace(brRegex, "\r\n")).select();
document.execCommand("copy");
$temp.remove();
}

</script>

However when you paste the result i get the following with the formatting tags visible:

<b>Mon 09 Oct - DY 7015 </b> 
Depart: London Gatwick Airport,  (LGW) at 17:05
Arrive: John F Kennedy Airport, New York (JFK) at 20:05 

I want the result input to be

Mon 09 Oct - DY 7015
Depart: London Gatwick Airport, (LGW) at 17:05
Arrive: John F Kennedy Airport, New York (JFK) at 20:05

or if this is not possible easily, then at the very least display without formatting but also without the tags

Mon 09 Oct - DY 7015
Depart: London Gatwick Airport, (LGW) at 17:05
Arrive: John F Kennedy Airport, New York (JFK) at 20:05

Any ideas?


回答1:


You can try this regex to remove your HTML tags: /<\/?[a-zA-Z]+\/?>/g

So, this should work :

$(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '')

Hope this helps!



来源:https://stackoverflow.com/questions/46381974/javascript-copy-to-clipboard-including-html-formatted-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!