Paste rich text into editable content div and save only bold and italic formatting

I want to insert some rich text with different fonts, font sizes, font weights, etc. into editable content div and ONLY keep courage and italics. Any idea how to do this?

The following code turns rich text into plain text when pasted into editable content div.

 $('[contenteditable]').on('paste',function(e) { e.preventDefault(); var text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Paste something..'); document.execCommand('insertText', false, text); }); 

I tried looking at the text variable in the above code, but it does not seem to be formatted.

+25
jquery html
Jan 21 '14 at 12:06 on
source share
3 answers

Here's a working demo: http://jsfiddle.net/SJR3H/7/

 $(document).ready(function(){ $('[contenteditable]').on('paste',function(e) { e.preventDefault(); var text = (e.originalEvent || e).clipboardData.getData('text/html') || prompt('Paste something..'); var $result = $('<div></div>').append($(text)); $(this).html($result.html()); // replace all styles except bold and italic $.each($(this).find("*"), function(idx, val) { var $item = $(val); if ($item.length > 0){ var saveStyle = { 'font-weight': $item.css('font-weight'), 'font-style': $item.css('font-style') }; $item.removeAttr('style') .removeClass() .css(saveStyle); } }); // remove unnecesary tags (if paste from word) $(this).children('style').remove(); $(this).children('meta').remove() $(this).children('link').remove(); }); }); 

Edit later: http://jsfiddle.net/SJR3H/8/

I added the following lines:

 $item.replaceWith(function(){ return $("<span />", {html: $(this).html()}); }); 

It actually replaces the html tags with span s. There you can optionally select tags that were in the source text ( h1 , p , etc.), styling them as you wish.

+21
Mar 04
source share

Start with the code:

 //on paste var text = (e.originalEvent || e).clipboardData.getData('text/plain') //html in clipboard are saved as Plain Unicode string , getData('text/plain') //return data as string, //if MIME TYPE 'text/html' is used you will get data as html with style attributes // insert text document.execCommand('insertText', false, text); //this will simply insert the text to contenteditable div. //so there is no chance of knowing recieved text is bold / italics. 

(1) we need to get the data as html to get the style properties: fontWeight, fontStyle.

(2) reduce html for the required style format,

(3) add to the contenteditable div.

! important:

we depend on the clipboard API to get the data.

It is not fully supported by newer browsers, please check the links below:

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/paste

http://caniuse.com/clipboard

therefore, in the IE browser, it does not work as expected.

the data format argument we pass to getData () is different in the IE browser:

http://msdn.microsoft.com/en-us/library/ie/ms536436(v=vs.85).aspx

so we get only the regular string from the getData () method I checked in IE 9.0.8112.16421 (not updated),

I am not aware of IE version 10, 11.

I encoded this way, if getData ("Html") is supported in 10.11 code, the requirements will be met.

Code works: Like @Cristi, we get all the html elements.

iterating through them, instead of changing style attributes, we use tags.

bold tags and italic tags.

Iterations are performed asynchronously because pasting large text content may be browser freezing.

I tested Chrome, Firefox.

 pasteArea.addEventListener('paste', function(e) { // prevent pasting text by default after event e.preventDefault(); var clipboardData = {}, rDataText, rDataHTML; clipboardData = e.clipboardData; rDataHTML = clipboardData.getData('text/html'); rDataPText = clipboardData.getData('text/plain'); if (rDataHTML && rDataHTML.trim().length != 0) { //Function Call to Handle HTML return false; // prevent returning text in clipboard } if (rDataPText && rDataPText.trim().length != 0) { //Function Call to Handle Plain String return false; // prevent returning text in clipboard } }, false); // Handle Plain Text function PlainTextHandler(pText) { // Remove Line breaks // append to contenteditable div - using range.insertNode() // document.execCommand(); had issue in ie9 so i didn't used it } // Handle HTML function formatHtml(elem, complete) { var flag_italic = false; var flag_weight = false; var fontStyle; var fontWeight; if (elem.nodeType == 1) { // only pass html elements // get style in css var CSSStyle = window.getComputedStyle(elem); fontStyle = CSSStyle.fontStyle; fontWeight = CSSStyle.fontWeight; // get style defined by inline var InlineStyle = elem.style; inlineFontStyle = InlineStyle['font-style']; inlineFontWeight = InlineStyle['font-weight']; if (inlineFontStyle && inlineFontStyle.trim() != '') fontStyle = inlineFontStyle; if (inlineFontWeight && inlineFontWeight.trim() != '') fontWeight = inlineFontWeight; // get style defined in MSword var msStyle = elem.getAttribute('style'); if (/mso-bidi/.test(msStyle)) { var MSStyleObj = {}; var styleStrArr = msStyle.split(";"); for (i = 0; i < styleStrArr.length; i++) { var temp = styleStrArr[i].split(":"); MSStyleObj[temp[0]] = temp[1]; } fontStyle = MSStyleObj['mso-bidi-font-style']; fontWeight = MSStyleObj['mso-bidi-font-weight']; } if (fontStyle && fontStyle == 'italic') flag_italic = true; // flag true if italic if (fontWeight && (fontWeight == 'bold' || 600 <= (+fontWeight))) flag_weight = true; // flag true if bold - 600 is semi bold // bold & italic are not applied via style // these styles are applied by appending contents in new tags string & bold if (flag_italic && flag_weight) { var strong = document.createElement('strong'); var italic = document.createElement('i'); strong.appendChild(italic); newtag = strong; } else { if (flag_italic) { newtag = document.createElement('i'); } else if (flag_weight) { newtag = document.createElement('strong'); } else { // remove un wanted attributes & element var tagName = elem.tagName; // strong are not skipped because, by creating new unwanted attributes will be removed if (tagName == 'STRONG' || tagName == 'B') { newtag = document.createElement('strong'); } else if (tagName == 'I') { newtag = document.createElement('i'); } else { newtag = document.createElement('span'); } } } // content appended var elemHTML = elem.innerHTML; if (flag_italic && flag_weight) { newtag.childNodes[0].innerHTML = elemHTML; } else { newtag.innerHTML = elemHTML; } // curr element is replaced by new elem.parentNode.insertBefore(newtag, elem); elem.parentNode.removeChild(elem); } complete() // completed one iteration } 

Violin: http://jsfiddle.net/aslancods/d9cfF/7/

+5
Mar 08 '14 at 20:51
source share

I have been using this on my website for a long time

 $(document).on('paste','#tesc', function() { setTimeout(function() { asd = strip_tags( $('#tesc').html(), '<b><b/><i></i>'); $('#tesc').html( asd ); },100); }); function strip_tags (input, allowed) { /* http://kevin.vanzonneveld.net*/ if ( input == undefined ) { return ''; } allowed = (((allowed || "") + "").toLowerCase().match(/<[az][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>) var tags = /<\/?([az][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi; return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; }); } 
+3
Mar 08 '14 at 20:59
source share



All Articles