Why not just using RegEx and do something like (just as example):
const wordCounter = (myString,mySearchString) => ((myString).match(new RegExp('\\b'+mySearchString+'\\b',"g")) || []).length;
let pinfo;
let itext;
let isearch;
function setup() {
noCanvas();
createElement("label").html("Search String: ");
isearch = createInput("Imagine");
createElement("br");
createElement("label").html("Text To Search: ");
itext = createInput("Imagine there's no heaven | It's easy if you try | No hell below us | Above us, only sky | Imagine all the people | Livin' for today | Ah | Imagine there's no countries | It isn't hard to do | Nothing to kill or die for | And no religion, too | Imagine all the people | Livin' life in peace | You | You may say I'm a dreamer | But I'm not the only one | I hope someday you'll join us | And the world will be as one | Imagine no possessions | I wonder if you can | No need for greed or hunger | A brotherhood of man | Imagine all the people | Sharing all the world | You | You may say I'm a dreamer | But I'm not the only one | I hope someday you'll join us | And the world will live as one");
itext.input(function() {
pinfo.html("The word " + isearch.value() + " was found " + wordCounter(this.value(),isearch.value()) + " time(s)");
});
pinfo = createP();
}

Cheers
— mnse