Extracting text from a contentEditable div

Unfortunately you do still have to handle this for the pre case individually per-browser (I don’t condone browser detection in many cases, use feature detection…but in this case it’s necessary), but luckily you can take care of them all pretty concisely, like this:

var ce = $("<pre />").html($("#edit").html());
if($.browser.webkit) 
  ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; });    
if($.browser.msie) 
  ce.find("p").replaceWith(function() { return this.innerHTML  +  "<br>"; });
if($.browser.mozilla || $.browser.opera ||$.browser.msie )
  ce.find("br").replaceWith("\n");

var textWithWhiteSpaceIntact = ce.text();

You can test it out here. IE in particular is a hassle because of the way is does &nbsp; and new lines in text conversion, that’s why it gets the <br> treatment above to make it consistent, so it needs 2 passes to be handled correctly.

In the above #edit is the ID of the contentEditable component, so just change that out, or make this a function, for example:

function getContentEditableText(id) {
    var ce = $("<pre />").html($("#" + id).html());
    if ($.browser.webkit)
      ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; });
    if ($.browser.msie)
      ce.find("p").replaceWith(function() { return this.innerHTML + "<br>"; });
    if ($.browser.mozilla || $.browser.opera || $.browser.msie)
      ce.find("br").replaceWith("\n");

    return ce.text();
}

You can test that here. Or, since this is built on jQuery methods anyway, make it a plugin, like this:

$.fn.getPreText = function () {
    var ce = $("<pre />").html(this.html());
    if ($.browser.webkit)
      ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; });
    if ($.browser.msie)
      ce.find("p").replaceWith(function() { return this.innerHTML + "<br>"; });
    if ($.browser.mozilla || $.browser.opera || $.browser.msie)
      ce.find("br").replaceWith("\n");

    return ce.text();
};

Then you can just call it with $("#edit").getPreText(), you can test that version here.

Leave a Comment