Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

javascript - REGEX - Highlight part over 19 chars

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...