How do I change the color of all words that start with the #
character to blue in a content-editable div while the user is typing. All it does right now is color all the matches but only if they come after a no matched word. Like this:
#life
randomness #death
more nothing #trees
But this doesn't work:
I ate an apple #yum
#doctoraway
#healthy
#diet
here's a fiddle: http://jsfiddle.net/GEm75/
The way I am doing it now is by wrapping each match in a span and then styling it with css. I encountered a problem where the non-matched text after hashtag was still the same color as the hashtag. I solved that, but very inefficiently and I desperately want an alternative. Here's my code:
<div id="box" style="border: 1px solid black; height: 10em" contenteditable="true">
</div>
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
var inp = $('#box');
//select the box div
var text = '';
//#box's default value
inp.on('keyup', function(e) {
text = inp.html();
var matches_hash = text.match(/(^|\s)#(\w+)/g);
if (matches_hash) {
text = text.replace(/(^|\s)#(\w+)/g, "</span><span class='hashtag'> #$2</span><span class='else'>");
inp.html(text);
placeCaretAtEnd(document.getElementById('box'));
}
});
</script>
I am wondering if there is a more efficient way of doing this. Also the problem where hashtags have to be separated by non hashtag text. I ran my regular expressions through a regex tester and it worked fine.
the function placeCaretAtEnd(el) was made by someone else, I did not make it. But all it does is place the caret at the end of the editable div.
If you have questions drop me a comment
Please help me.