JSFiddle - React, Tailwind, and code Playground

by Thomas Schoffelen

HTML

<textarea id="fulltext">The brown fox jumps over the white sheep. That is a quite foxy lady, but I am the only real fox in here. I used to think foxes were scary, until I saw a fox in my yard yesterday.</textarea>Match word:
<input type="text" id="match" value="fox" />
<input type="button" onclick="findWord()" value="Find word" />
<div id="output"></div>

CSS

textarea {
    width: 100%;
    height: 120px;
    margin-bottom: 12px;
}
body {
    padding: 50px;
    font-family: Helvetica, Arial;
    color: #333;
}
#output {
    color: green;
    padding-top: 12px;
    font-weight: bold;
}
}

JavaScript

function findWord() {
    var outputDiv = $('#output');
    var searchText = $('#fulltext').val();
    var wordMatch = $('#match').val().toLowerCase();

    if (wordMatch == '') {
        alert('Please enter a word!');
        return;
    }
    outputDiv.empty();

    // Simple method: matches also partials ('fox' in 'foxy')
    var m = searchText.match(new RegExp(wordMatch.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "ig"));
    outputDiv.append('<div>' + (m ? m.length : 0) + ' partial matches</div>');

    // Advanced method: matched only full words.
    // This one first splits the string in words, and then loops 
    // through all of them (potentially slow with very longs texts)
    var count = 0;
    var words = searchText.split(' ');
    for (x in words) {
        if (words[x].toLowerCase() == wordMatch) {
            count++;
        }
    }
    outputDiv.append('<div>' + count + ' full word matches</div>');
}