Fred J. Fred J. - 4 months ago 8
CSS Question

Live styling part of text on list items to match user input

A Meteor client code receives a live input from user as being typed into an input box via the template


On the page there is list items with text in each. I need to apply a style to the part of the text in any of the list items which matches what the user is typing.

My attempt is not applying any styling at all.

How can it be done? Thanks

'keyup .check-filter': function(event) {

showMatches: (userInput) => {
if (userInput.length > 3) {
//this is not doing the job for me.
$('li').html($('li').html().replace('/' + userInput + '/gi', '<span class="myCSS">' + $1 + '< /span>'));



For variables you need to use RegExp, also your function will add a span around every character group, which will make it fail when replace from the fifth letter, so you need to clear that part as well, not mentioned when deleting characters.

// global, app specific, variables
var myApp = {
  userInput : {
    firstTime : true,
    newValue : "",
    lastValue : ""

document.querySelector('input').addEventListener('input', function(e) {  
  myApp.userInput.newValue =;

  if (myApp.userInput.newValue.length > 3 || !myApp.userInput.firstTime) {
    if (!myApp.userInput.firstTime) {
      var re = new RegExp('<span class="myCSS">' + 
                          myApp.userInput.lastValue + 

      $( "li" ).each(function( index ) {
        $( this ).html($( this ).html().replace(re, myApp.userInput.lastValue));


    myApp.userInput.firstTime = false;
    var re = new RegExp(myApp.userInput.newValue,'gi');    

    $( "li" ).each(function( index ) {
      $( this ).html($( this ).html().replace(re, '<span class="myCSS">' + myApp.userInput.newValue + '</span>'));      

  myApp.userInput.lastValue = myApp.userInput.newValue;  
.myCSS {
  color: red
<script src=""></script>

  <li>Hello there, there is 2 or more word duplicates in  here</li>
  <li>This has 2 or more words as well, but is a completely different sentence</li>

Test input: <input type="text"/>