0

I have a div which is content editable, and JS function to search the input for certain words. If a match is found, the content od the div turns blue, but I want only the matched word to turn blue. How can I do this? Here is my JS...

   function init() {

window.setInterval(function() {

    var div = document.getElementById("texty");
    var html = div.innerHTML;
    var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];

    for(var i = 0; i < buzzword.length; i++) 
    {
        var regex = new RegExp(buzzword[i], 'g');
        html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
    }

    div.innerHTML = html;

}, 100);


}

and my HTML is this...

<div id="texty" contenteditable="true" onfocus="init()"></div>

1 Answers1

0

Get the html of the div then do a regex replace and add a span around the word. Code would look something like this:

    var escape= function(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
    };

    var div = document.getElementById("texty");
    var html = div.innerHTML;
    var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
    for(var i = 0; i < buzzword.length; i++)
    {
        var regex = new RegExp(escape(buzzword[i]), 'g');
        html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
    }

    div.innerHTML = html;
Phillip Burch
  • 459
  • 5
  • 11
  • Thanks! This code looks good, but it's having no effect on my webpage. Any idea why? :S –  Sep 07 '13 at 14:51
  • There could be several reasons. Can't really tell you without looking at your page. Don't directly copy my code, but instead, look at what it does and tailor it to fit your needs. – Phillip Burch Sep 07 '13 at 14:54
  • I've edited my question to show my html, and my new JS using the code you showed me. I can't find any errors in it, atleast not spelling or syntax ones! –  Sep 07 '13 at 14:59
  • Accepted! :) Do you know why after the span is applied, my cursor is moved back to the beginning, and cannot be moved forward again? O.o –  Sep 07 '13 at 15:16
  • 1
    yes, but thats a very larger problem. Please see this question: http://stackoverflow.com/questions/1181700/set-cursor-position-on-contenteditable-div – Phillip Burch Sep 07 '13 at 15:19