REGEX - Highlight part over 19 chars

2020-02-05 11:26发布

Hi,

I have some text inside div[contenteditable="true"] and I should highlight (span.tooLong) part which goes over the 19 character limit. Content in div may have HTML tags or entities and those should be ignored when counting to 19.

Twitter has similar way to highlight too long tweet:

Twitter's highlight

Examples:

  • This is textThis is text
  • This is just too long textThis is just too lo<span class="tooLong">ng text</span>
  • This <b>text</b> has been <i>formatted</i> with HTMLThis <b>text</b> has been <span class="tooLong"><i>formatted</i> with HTML</span>

How can I implement this in JavaScript?

(I want to use regular expressions as much as possible)

2条回答
smile是对你的礼貌
2楼-- · 2020-02-05 11:53

Here's an answer that uses my Rangy library. It uses the Class Applier and TextRange modules to apply styling on character ranges within the editable content while preserving the selection. It also uses a configurable debounce interval to prevent sluggishness in editor performance. Also, it should work on old IE.

Demo: http://jsfiddle.net/timdown/G4jn7/2/

Sample code:

var characterLimit = 40;
var debounceInterval = 200;

function highlightExcessCharacters() {
    // Bookmark selection so we can restore it later
    var sel = rangy.getSelection();
    var savedSel = sel.saveCharacterRanges(editor);

    // Remove previous highlight
    var range = rangy.createRange();
    range.selectNodeContents(editor);
    classApplier.undoToRange(range);

    // Store the total number of characters
    var editorCharCount = range.text().length;

    // Create a range selecting the excess characters
    range.selectCharacters(editor, characterLimit, editorCharCount);

    // Highlight the excess
    classApplier.applyToRange(range);

    // Restore the selection
    sel.restoreCharacterRanges(editor, savedSel);
}

var handleEditorChangeEvent = (function() {
    var timer;

    function debouncer() {
        if (timer) {
            timer = null;
        }
        highlightExcessCharacters();
    }

    return function() {
        if (timer) {
            window.clearTimeout(timer);
        }
        timer = window.setTimeout(debouncer, debounceInterval);
    };
})();

function listen(target, eventName, listener) {
    if (target.addEventListener) {
        target.addEventListener(eventName, listener, false);
    } else if (target.attachEvent) {
        target.attachEvent("on" + eventName, listener);
    }
}

rangy.init();
var editor = document.getElementById("editor");
var classApplier = rangy.createClassApplier("overrun");

// Set up debounced event handlers
var editEvents = ["input", "keydown", "keypress", "keyup",
                  "cut", "copy", "paste"];

for (var i = 0, eventName; eventName = editEvents[i++]; ) {
    listen(editor, eventName, handleEditorChangeEvent);
}
查看更多
相关推荐>>
3楼-- · 2020-02-05 11:56

Okay... here's some code that I think will work for you, or at least get your started.

Basically, the regex you need to find everything over 19 characters is this:

var extra = content.match(/.{19}(.*)/)[1];

So, I put together a sample document of how you might use this.

Take a look at the DEMO.

Here's the Javascript I'm using (I'm using jQuery for the locators here, but this can easily be modified to use straight Javascript... I just prefer jQuery for stuff like this)...

$(document).ready(function() {
  $('#myDiv').keyup(function() {
    var content = $('#myDiv').html();
    var extra = content.match(/.{19}(.*)/)[1];

    $('#extra').html(extra);

    var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
    $('#sample').html(newContent);
  });
});

Basically, I have three DIVs setup. One for you to enter your text. One to show what characters are over the 19 character limit. And one to show how you might highlight the extra characters.

My code sample does not check for html tags, as there are too many to try and handle... but should give you a great starting point as to how this might work.

NOTE: you can view the complete code I wrote using this link: http://jsbin.com/OnAxULu/1/edit

查看更多
登录 后发表回答