0

I'm trying to change an example from https://www.w3schools.com/howto/howto_js_autocomplete.asp. I would like to autocomplete that will start searching for letters in the middle of words not just from the beginning of a word. I managed to do it but I can not make the letters bold.

Sorry for my engilsh

Example:

If i write in input "stralia" a suggestion would be looks like Australia.

Edit:
@Ali Sheikhpour Your solution works almost perfectly. But i have one small bug. Right now suggestion work like i show up in my up example but when i try for example: If i write "an" in input suggestion will be show me:
"Afghanistan"
"Angola"
"Andorra"
I suppose that the problem right now are capital letters.

  • 1
    Can you show a [mcve]? –  Oct 04 '18 at 18:04
  • Hi simple_code, welcome to Stack Overflow! @jdv was getting at this already, but I'll try to explain more clearly: when you ask a question to get help with code that's not working, it's strongly encouraged to include working code that you have tried so far, with an explanation of what it's not doing correctly, and any attempts you have made to get it to work correctly, and how they failed. This will help other users see what you have done and give you suggestions on what to do next :) – MyStackRunnethOver Oct 04 '18 at 20:04

1 Answers1

0

this is the main part that compares input value against the array:

if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase())

You just need to change it to the following to check if the array item contains the key string:

if ( (arr[i].toUpperCase()).indexOf(val.toUpperCase()) != -1)

Also to make the keyword bold:

current code:

 b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
 b.innerHTML += arr[i].substr(val.length);

Alternative solution which I think is more simple even for the original post:

 b.innerHTML = arr[i].replace(val,"<strong>" + val + "</strong>");

in Order to ignore uppercase differences you may compare values in Lowercase and then use this answer to make first letter Uppercase again::

 b.innerHTML = (arr[i].toLowerCase()).replace(val.toLowerCase(),"<strong>" + val + "</strong>");
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • Thanks, this is a very cool solution. but I'm still looking for a way to works like i show in my edited questios –  Oct 04 '18 at 19:25
  • It's very very nice. Can I have one more question? I show in my question. –  Oct 05 '18 at 15:37
  • I have updated the answer again. Please Vote up the answer if the edit was helpful. @simple_code – Ali Sheikhpour Oct 05 '18 at 22:01