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:
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)
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:
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:
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)...
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