We adapted the copyToClipboard function to make it work with our application. The changes were as follows:
- change the input to textarea to skip line breaks;
- change the text () function to html () so that the HTML is passed;
- use regex to replace each HTML br with a translation string;
- use another regex to remove the remaining HTML. HTML in our application must have
<b> and <br> tags, so a simple regular expression should work, as well as process an odd tag that may be present.
Here is our adapted feature as well as comments:
// Note: original replace used to strip HTML tags from https://stackoverflow.com/questions/5002111/javascript-how-to-strip-html-tags-from-string ReactiveRaven. // However, replaced closing (>|$) with > as I don't understand why the check for $ is there, as it implies that $ is part of an HTML tag. // Our requirement highly constrains the HTML, to mainly have <br> and <b> tags, so the general objection to parsing HTML with regex // as at https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags community wiki is not applicable. // BTW, that page is very entertaining! function copyToClipboard(element) { var $temp = $("<textarea>"); $("body").append($temp); var x = $(element).html().trim().replace(/<br>/g, '\n').replace(/<\/?[^>]+>/g, ''); $temp.val(x).select(); document.execCommand("copy"); $temp.remove(); }
Btw, if anyone knows why the regular expression from the cited page had (> | $) that we changed to>, we would like to get an understanding of why the dollar sign we removed is required.
source share