Search code examples
jquerycopy-paste

find if a pasted content is html or plain text using jQuery


I am trying to clean the pasted content before I add it to my text area. so I use a call back, but if I use plain text then the content is not calling in the call back, only html text is getting called in the function. Is there a way to find if the content pasted into the text area is html content or plain content? When a content is pasted in my text area I am using this

var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('text/html');

but the above code holds good for html. but I need to know if the content is a html or plain text.


Solution

  • let sPlain = 'plain text'
            , sHtml = 'text <i>with tags</i>'
            , wrapped_sp = `<div>${sPlain}</div>`
            , wrapped_sh = `<div>${sHtml}</div>`
            , w2t_sp = $(wrapped_sp).text()
            , w2t_sh = $(wrapped_sh).text()
            , isplain_sp = ( w2t_sp == sPlain )
            , isplain_sh = ( w2t_sh == sHtml ) 
    
        console.log( "%s is %stext/plain", sPlain, isplain_sp ? "" : "NOT " );
        console.log( "%s is %stext/plain",  sHtml, isplain_sh ? "" : "NOT " );
    

    As answer to the original question specifically:

    let is_bufferText_plain = ( $(`<div>${bufferText}</div>`).text() == bufferText );
    if( is_bufferText_plain ){
      // do whatever is required if the bufferText content is text/plain
    }else{
      // do whatever is required if the bufferText content is text/html
    }