Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 text ? This is text
  • This is just too long text ? This is just too lo<span class="tooLong">ng text</span>
  • This <b>text</b> has been <i>formatted</i> with HTML ? This <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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...