JSFiddle - React, Tailwind, and code Playground

by Pris Wiz

HTML

<textarea id="text"></textarea>
<input id="query"></input>
<button id="search">Search</button>
<div id="hits"></div>
<div id="results"></div>

CSS

textarea {
    height: 8em;
    width: 32em;
}
p {
    margin:0;
    overflow: auto;
}
span {
    width: 4em;
    margin-right: 1em;
    text-align: right;
    float: left;
}

JavaScript

// string search by weegillis, aka, mtf

(function () {

    function search(q, t) {
        var h = [];
        var l = q.length;
        var n = t.length;
        for (i = 0; i < n; i++) {
            if (t.substr(i, l) === q) {
                h.push(i);
                i += l - 1;
            }
        }
        return h;
    }

    function output(h, t, q) {
        var l = q.length;
        var n = h.length;
        document.getElementById('hits').innerHTML = "<p>Found " + n + " hits.</p>";
        var r = document.getElementById('results');
        r.innerHTML = "";
        for (i = 0; i < n; i++) {
            r.innerHTML += "<p><span>" + h[i] + "</span> " + t.substr(h[i], l) + "</p>";
        }
    }

    function bundle() {
        var text = document.getElementById('text').value;
        var query = document.getElementById('query').value;
        output(search(query, text), text, query);
    }

    var go = document.getElementById('search');
    if (window.attachEvent) {
        go.attachEvent('onclick', bundle);
    } else {
        go.addEventListener('click', bundle, false);
    }
})();