JS进行复制文本(保留样式和不保留样式)

// 替换 html 特殊字符
export function replaceHtmlSymbol(html) {
  if (html == null) {
    return ''
  }
  return html.replace(/</gm, '&lt;')
    .replace(/>/gm, '&gt;')
    .replace(/"/gm, '&quot;')
    .replace(/(\r\n|\r|\n)/g, '<br/>')
}
import { replaceHtmlSymbol } from './util.js'

// 获取粘贴的纯文本
export function getPasteText(e) {
  const clipboardData = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData)
  let pasteText
  if (clipboardData == null) {
    pasteText = window.clipboardData && window.clipboardData.getData('text')
  } else {
    pasteText = clipboardData.getData('text/plain')
  }

  return replaceHtmlSymbol(pasteText)
}

// 获取粘贴的html
export function getPasteHtml(e, filterStyle, ignoreImg) {
  const clipboardData = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData)
  let pasteText, pasteHtml
  if (clipboardData == null) {
    pasteText = window.clipboardData && window.clipboardData.getData('text')
  } else {
    pasteText = clipboardData.getData('text/plain')
    pasteHtml = clipboardData.getData('text/html')
  }
  if (!pasteHtml && pasteText) {
    pasteHtml = '<span>' + replaceHtmlSymbol(pasteText) + '</span>'
  }
  if (!pasteHtml) {
    return
  }

  // 过滤word中状态过来的无用字符
  const docSplitHtml = pasteHtml.split('</html>')
  if (docSplitHtml.length === 2) {
    pasteHtml = docSplitHtml[0]
  }
  // 过滤无用标签
  pasteHtml = pasteHtml.replace(/<\/?(meta|html|head|title|body|script|link|xml)( [\s\S]*?)*>/igm, '')
  // 去掉注释
  pasteHtml = pasteHtml.replace(/<!--.*?-->/mg, '')
  pasteHtml = pasteHtml.replace(/<!--?(\[)(\S|\s|[0-9])*?(\])--?>/mg, '')
  pasteHtml = pasteHtml.replace(/<o:p>[\n\r\s&nbsp;]*<\/o:p>/mg, '')
  pasteHtml = pasteHtml.replace(/<style(([\s\S])*?)<\/style>/mg, '')
  // 过滤 data-xxx href target 属性
  pasteHtml = pasteHtml.replace(/\s?data-.*?=('|")(\{?).+?(\}?)('|")/igm,   '')

  if (ignoreImg) {
    // 忽略图片
    pasteHtml = pasteHtml.replace(/<img.+?>/igm, '')
  }

  if (filterStyle) {
    // 过滤样式
    pasteHtml = pasteHtml.replace(/\s?(style)=('|").*?('|")/igm, '')
    // 过滤别的标签
    pasteHtml = pasteHtml.replace(/<\/?(h1|h2|h3|h4|h5|p|div|ul|i|ol|li|strong|b|a|button|u|hr|pre|em|font|sup|SUB|table|tbody|td|th|tr|br|col)([\s\S]*?)>/igm, '')
    if (!/</g.test(pasteHtml)) {
      pasteHtml = pasteHtml.replace(/(\r\n|\r|\n)/g, '')
    }
  } else {
    // 保留样式
    pasteHtml = pasteHtml.replace(/\s?class=('|").*?('|")/igm, '')
  }

  return pasteHtml
}
posted @ 2023-02-07 15:33  DL·Coder  阅读(432)  评论(0编辑  收藏  举报