0

I got an input field were a user can type keywords for example "jeans". When "jeans" have been typed into the input field a list of search suggestions comes up which contains the word or part of the word "jeans".

I would like to match the string typed in the input field with the text that is shown in the search suggestions, and make the text from the search suggestions which matches the text typed in the input field bold. So far I can return a text string of what is typed in the input field, and I can also return a text string of what the search suggestions contains. Now I would need to compare thoes two, and my best guess is to use match().

However i keep getting null as a result in my function below. I need to use plain Vanilla JS for the solution.

    //get the text from the search suggestions list as a string
    var searchSuggestList = document.getElementsByClassName('search-suggest__list')[0];
    var searchSuggestListText = searchSuggestList.innerText;

    //get value from input field as a string
    var searchSuggestInput = document.getElementsByClassName('js-search-suggest-input')[0].value

    var result = searchSuggestInput.match(searchSuggestListText);
Mikkel Fennefoss
  • 857
  • 1
  • 9
  • 32

1 Answers1

0

Since you're looking for the value of searchSuggestInput in searchSuggestListText, you need to invert your variables:

var result = searchSuggestListText.match(searchSuggestInput);

Keep in mind that searchSuggestInput will be treated as a regular expression. It's probably a good idea to read through the String.prototype.match() documentation before continuing with this approach, especially the section that describes how the method will return different results depending on the presence of the /g flag.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156