從 Word 複製文字貼到線上編輯器時,常會帶入一堆 span、font、o:p 之類的冗餘標籤與樣式。本文示範如何透過 JavaScript 一次清乾淨這些 Word 格式。
先取得編輯器內的內容,逐一移除每個元素的 class、style、font 屬性,再用正則表達式把殘留的 o:p、font、span 等標籤替換掉,最後把乾淨的內容寫回編輯器。
<input type="button" onclick="cleanWord();" value="Word清理" />
cleanWord = function(){
var editBody = FCKeditorAPI.GetInstance("text").EditorDocument.body;
var html = FCKeditorAPI.GetInstance("text").EditorDocument.body.innerText;
for(var intLoop=0;intLoop<editBody.all.length;intLoop++){
el=editBody.all[intLoop];
el.removeAttribute("className","",0);
el.removeAttribute("style","",0);
el.removeAttribute("font"," ",0);
}
html=html.replace(/<o:p> </o:p>/g,"");
html=html.replace(/o:/g,"");
html=html.replace(/<font>/g,"");
html=html.replace(/<span>/g,"");
html=html.replace(/<SPANlang=EN-US>/g,"");
FCKeditorAPI.GetInstance("text").EditorDocument.body.innerText=html;
}
這個做法特別適合搭配 FCKeditor 這類富文本編輯器,讓貼上內容乾淨、版面統一。