使用JavaScript清除Microsoft Word粘贴文本

问题描述 投票:23回答:9

我正在使用'contenteditable'<div/>并启用PASTE。

令人惊讶的是从Microsoft Word的剪贴板副本粘贴的标记代码量。我正在与此作斗争,并且已经使用Prototypes的stripTags()函数(不幸的是似乎不能让我保留一些标签)获得大约1/2的方式。

然而,即使在那之后,我最终还是会抽出大量不必要的标记代码。

所以我的问题是,是否有一些功能(使用JavaScript),或者我可以使用哪种方法来清理大部分不需要的标记?

javascript ms-word paste
9个回答
21
投票

这是我写完的功能,它完成了相当好的工作(据我所知,无论如何)。

如果有人有,我当然愿意接受改进建议。谢谢。

function cleanWordPaste( in_word_text ) {
 var tmp = document.createElement("DIV");
 tmp.innerHTML = in_word_text;
 var newString = tmp.textContent||tmp.innerText;
 // this next piece converts line breaks into break tags
 // and removes the seemingly endless crap code
 newString  = newString.replace(/\n\n/g, "<br />").replace(/.*<!--.*-->/g,"");
 // this next piece removes any break tags (up to 10) at beginning
 for ( i=0; i<10; i++ ) {
  if ( newString.substr(0,6)=="<br />" ) { 
   newString = newString.replace("<br />", ""); 
  }
 }
 return newString;
}

希望这对你们中的一些人有所帮助。


3
投票

你可以使用完整的CKEditor清洁粘贴,或look at the source


3
投票

我用这个:

$(body_doc).find('body').bind('paste',function(e){
                var rte = $(this);
                _activeRTEData = $(rte).html();
                beginLen = $.trim($(rte).html()).length; 

                setTimeout(function(){
                    var text = $(rte).html();
                    var newLen = $.trim(text).length;

                    //identify the first char that changed to determine caret location
                    caret = 0;

                    for(i=0;i < newLen; i++){
                        if(_activeRTEData[i] != text[i]){
                            caret = i-1;
                            break;  
                        }
                    }

                    var origText = text.slice(0,caret);
                    var newText = text.slice(caret, newLen - beginLen + caret + 4);
                    var tailText = text.slice(newLen - beginLen + caret + 4, newLen);

                    var newText = newText.replace(/(.*(?:endif-->))|([ ]?<[^>]*>[ ]?)|(&nbsp;)|([^}]*})/g,'');

                    newText = newText.replace(/[·]/g,'');

                    $(rte).html(origText + newText + tailText);
                    $(rte).contents().last().focus();
                },100);
            });

body_doc是可编辑的iframe,如果您使用的是可编辑的div,则可以删除.find('body')部分。基本上它会检测粘贴事件,检查位置是否清除新文本,然后将清理后的文本放回粘贴的位置。 (听起来令人困惑......但它并不像听起来那么糟糕。

需要setTimeout,因为在实际粘贴到元素中之前无法获取文本,粘贴开始时会立即粘贴事件。


2
投票

如何使用“粘贴为纯文本”按钮显示<textarea>,允许用户将文本粘贴在那里?这样,所有标签都会被剥离。这就是我对CMS的处理方式;我放弃了试图清理Word的烂摊子。


0
投票

我很久以前做过类似的事情,我在富文本编辑器中完全清理了这些内容,并将字体标签转换为样式,brs转换为p等,以使其在浏览器之间保持一致,并防止某些丑陋的东西通过粘贴进入。我接受了我的递归函数并除掉了核心逻辑之外的大部分内容,这可能是一个很好的起点(“结果”是一个累积结果的对象,可能需要第二遍转换为字符串),如果这就是你需要的:

var cleanDom = function(result, n) {
var nn = n.nodeName;
if(nn=="#text") {
    var text = n.nodeValue;

    }
else {
    if(nn=="A" && n.href)
        ...;
    else if(nn=="IMG" & n.src) {
        ....
        }
    else if(nn=="DIV") {
        if(n.className=="indent")
            ...
        }
    else if(nn=="FONT") {
        }       
    else if(nn=="BR") {
        }

    if(!UNSUPPORTED_ELEMENTS[nn]) {
        if(n.childNodes.length > 0)
            for(var i=0; i<n.childNodes.length; i++) 
                cleanDom(result, n.childNodes[i]);
        }
    }
}

0
投票

这非常适合从HTML文本中删除任何注释,包括来自Word的注释:

function CleanWordPastedHTML(sTextHTML) {
  var sStartComment = "<!--", sEndComment = "-->";
  while (true) {
    var iStart = sTextHTML.indexOf(sStartComment);
    if (iStart == -1) break;
    var iEnd = sTextHTML.indexOf(sEndComment, iStart);
    if (iEnd == -1) break;
    sTextHTML = sTextHTML.substring(0, iStart) + sTextHTML.substring(iEnd + sEndComment.length);
  }
  return sTextHTML;
}

0
投票

有一个类似的问题,换行被计为字符,我不得不删除它们。

$(document).ready(function(){

  $(".section-overview textarea").bind({
    paste : function(){
    setTimeout(function(){
      //textarea
      var text = $(".section-overview textarea").val();
      // look for any "\n" occurences and replace them
      var newString = text.replace(/\n/g, '');
      // print new string
      $(".section-overview textarea").val(newString);
    },100);
    }
  });
  
});

-1
投票

你能粘贴到隐藏的textarea,从同一个textarea复制,并粘贴到你的目标?


-4
投票

讨厌说出来,但我最终放弃让TinyMCE以我想要的方式处理Word垃圾。现在,每当用户的输入包含某些HTML(例如,查找<span lang="en-US">)时,我就会向我发送一封电子邮件,并且我会手动更正。

© www.soinside.com 2019 - 2024. All rights reserved.