如何去掉从word中粘贴文本的格式

 

由于这个问题普遍困扰这众多技术爱好者,故将此发表出来,以供大家共享。本技术已经成功应用到实际项目中。

在jsp页面中:
<div id="Temp_HTML" style="VISIBILITY: hidden; OVERFLOW: hidden; POSITION: absolute; WIDTH: 1px; HEIGHT: 1px"></div>
<textarea name="sendFileRemark" cols="50" rows="10" <%=readOnly%> onpaste="return onPaste();" onSelect="storeCaret4Mouse(this);" onClick="storeCaret4Mouse(this);" onKeyup="storeCaret4Key(event,this);"><%=sendFileRemark%></textarea>

在js文件中:
// 粘贴时自动检测是否来源于Word格式
function onPaste() {
var sHTML = GetClipboardHTML() ;
var re = /<\w[^>]* class="?MsoNormal"?/gi ;
if ( re.test( sHTML ) )
{
   if ( confirm( "你要粘贴的内容好象是从Word中拷出来的,有可能出现乱码,是否要先清除Word格式再粘贴?" ) )
   {
    cleanAndPaste( sHTML ) ;
    return false;
   }
}
return true;
}

//聪剪贴板中得到内容
function GetClipboardHTML() {
var oDiv = document.getElementById("Temp_HTML")
oDiv.innerHTML = "" ;

var oTextRange = document.body.createTextRange() ;
oTextRange.moveToElementText(oDiv) ;
oTextRange.execCommand("Paste") ;

var sData = oDiv.innerHTML ;
oDiv.innerHTML = "" ;

return sData ;
}

//将聪word中中得到的内容去掉格式
function cleanAndPaste( html ) {
// Remove all SPAN tags
html = html.replace(/<\/?SPAN[^>]*>/gi, "" );
// Remove Class attributes
html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
// Remove Style attributes
html = html.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, "<$1$3") ;
// Remove Lang attributes
html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
// Remove XML elements and declarations
html = html.replace(/<\\?\?xml[^>]*>/gi, "") ;
// Remove Tags with XML namespace declarations: <o:p></o:p>
html = html.replace(/<\/?\w+:[^>]*>/gi, "") ;
// Replace the &nbsp;
html = html.replace(/&nbsp;/, " " );
// Transform <P> to <DIV>
var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)","gi") ; // Different because of a IE 5.0 error
html = html.replace( re, "$2" ) ;
if(html.length>0){
   var i = html.indexOf(">");
   html = html.substring(i+1);
}
//document.sendform.sendFileRemark.value=html ;
insertAtCaret(html);

}

//在当前光标位置插入聪word中得到且去掉了格式的文本
function insertAtCaret(html) {
var obj = document.sendform.sendFileRemark;
if (obj.createTextRange && obj.caretPos) {
   var caretPos = obj.caretPos;
   caretPos.text =caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? html + ' ' : html;
    } else {
        obj.value = html;
    }
}

//当操作鼠标时记录下当前位置
function storeCaret4Mouse(textEl){
    if(textEl.createTextRange){
        textEl.caretPos = document.selection.createRange().duplicate();
    }
}

//当操作键盘时记录下当前位置
function storeCaret4Key(e,textEl) {
var key;
if(navigator.userAgent.indexOf("Firefox")>0){
   key=e.which;
    } else {
    key=e.keyCode;
    }
    //按enter、backspace、delete、tab、空格、上下左右箭头、home、end、上一页、下一页时需要记录光标的位置
if(key==13 || key==8 || key==46 || key==9 || key==32 || key==38 || key==40 || key==37 ||key==39 || key==36 || key==35 || key==33 || key==34){
    storeCaret4Mouse(textEl)
    }
}