mySentence = "Apple, boOk? BOoks; booKEd. BookMark, 'BookmarkeD', bOOkmarks! bookmakinG, Banana; bE, BeEn, beFore." function replacer(mySentence, hl_term, hl_re) { console.log('mySentence [raw]:', mySentence) console.log('hl_term:', hl_term, '| hl_term.length:', hl_term.length) cutoff = hl_term.length; console.log('cutoff:', cutoff) // `.match()` willconveniently collectcollects multiple matched items // (including partial matches) into an [array] const hl_terms = mySentence.toLowerCase().match(hl_re, hl_term); if (hl_terms == null) { console.log('No matches to hl_term "' + hl_term + '"; echoing input string then exiting ...') return mySentence; } console.log('hl_terms:', hl_terms) for (let i = 0; i < hl_terms.length; i++) { console.log('----------------------------------------') console.log('[' + i + ']:', hl_terms[i], '| length:', hl_terms[i].length, '| parseInt(0.7(length)):', parseInt(0.7*hl_terms[i].length)) // TEST: if (hl_terms[i].length >= cutoff*10) { if (cutoff >= parseInt(0.7 * hl_terms[i].length)) { var match_term = hl_terms[i].toString(); console.log('matched term:', match_term, '[cutoff length:', cutoff, '| 0.7(matched term length):', parseInt(0.7 * hl_terms[i].length)) const match_re = new RegExp(`(\\b${match_term}\\b)`, 'gi') mySentence = mySentence.replaceAll(match_re, '<font style="background:#ffe74e">$1</font>'); } else { var match_term = hl_terms[i].toString(); console.log('NO match:', match_term, '[cutoff length:', cutoff, '| 0.7(matched term length):', parseInt(0.7 * hl_terms[i].length)) } } return mySentence; } // TESTS: // const hl_term = 'be'; // const hl_term = 'bee'; // const hl_term = 'before'; // const hl_term = 'book'; const hl_term = 'bookma'; // const hl_term = 'Leibniz'; // This regex matches from start of word: const hl_re = new RegExp(`(\\b${hl_term}[A-z]*)\\b`, 'gi') mySentence = replacer(mySentence, hl_term, hl_re); console.log('mySentence [processed]:', mySentence)