Search code examples
javascriptstringtextboxcontain

If textbox contain a specific string do some function - javascript


I am wondering how to search specific string in big textbox (which contains 200 words) so I can make function to color them. Ex. In textbox there is a sentence "my dog is happy" and i want string "dog" to become red by button or sth else. Is it possible???


Solution

  • Yes, it is possible. But don't use a text box or text area, use a div with contenteditable = "true":

    <div id="editableDiv" class="editable" contenteditable="true">
        This is a sentence containing 'dog'.<br />
        You can edit the contents of this div.
    </div>
    <button id="highlightBtn">Highlight "dog"</button>
    <script type="text/javascript">
       highlightBtn.onclick = function() {
             var elem = document.getElementById('editableDiv');
             elem.innerHTML = elem.innerHTML.replace(/dog/g, 
                                '<span class="redText">dog</span>');
       }
     </script>
    

    And don't forget to create the classes redText and editable in your stylesheet:

    .editable {
        padding: 5px;
        border: dashed 1px black;
    }
    .redText {
        color: red;
    }
    

    JSFiddle: http://jsfiddle.net/ProgramFOX/UMMPh/