Pages

Sunday, December 26, 2010

Finding Words In Text Using JS RegExp

/**
 * Web application to search sentences that contain a word
 * supplied. 
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 27, 2010
 * @version : 1.0
 */


<div id="satu">
    This is a text. So you can do more with this one.
    Then make sure you type the word, not just a char
</div>
<input type="text" id="input"/>
<input type="button" value="Search"
     onclick="lol(document.getElementById('input').value)"/>
<div id="dua"></div>


<script>

function FindingWord(word){

    var doc = document.getElementById('satu');
    var text = doc.innerHTML;
    var desp = text.split(/[.]/g);

    var dua = document.getElementById('dua');
    var ol = document.createElement('ol');

    var pattern = new RegExp(word,"g");

    for(i=0;i&lt;desp.length;i++){
        code = desp[i].search(pattern);
        if(code!=-1){
            var li  = document.createElement('li');
            li.innerHTML = desp[i];
            dua.innerHTML = '';      
            ol.appendChild(li);
            dua.appendChild(ol);
        }
    }

}


</script>

No comments:

Post a Comment