search suggestion based on any letter of string

536 Views Asked by At

i am trying to write some java script code the auto suggest based on pretrial strings so to speak

here an example of what i mean:

if we have array of strings => [ 'text' , 'apple' , 'texas' , 'time' , 'java' , 'java script' , 'pen' ]

what i want to achieve is this : when the user type ==> "te" the function should return this ==> 'text' and 'texas'

BUT

if user type ==> "t*e" OR "t e" with space between the function should return this ==> 'text' , 'texas' , AND 'time' since it contains the tow letters no matter the oreder

the same if user type ==> "p*e" OR "p e" the result should be ==> 'apple' and 'pen' since booth contain the letters 'p' and 'e'

here what i have done so far

const nameInput = document.getElementById('name')

const names = [ 'text' , 'apple' , 'texas' , 'time' , 'java' , 'java script' , 'pen' ]

nameInput.addEventListener('keyup', ()=> {
  // console.log(nameInput.value)
const text = nameInput.value.trim().replace(/\s/g, '')
// console.log(text)
const a = names.filter(name => name.includes(text))
console.log(a)
})
<input type="text" placeholder="search"  id="name">

1

There are 1 best solutions below

3
Tushar Gupta On

As per your post t*e is failing as you don't catch them up in your regex. A more robust way is to replace all alphanumeric characters. You can quickly do it by a slight regex change to /[\W_]+/g

 const text = nameInput.value.trim().replace(/[\W_]+/g, '')

Working Code below

const nameInput = document.getElementById('name')

const names = ['text', 'apple', 'texas', 'time', 'java', 'java script', 'pen']

nameInput.addEventListener('keyup', () => {
  // console.log(nameInput.value)
  const text = nameInput.value.trim().replace(/[\W_]+/g, '')
  // console.log(text)
  const a = names.filter(name => name.includes(text))
  console.log(a)
})
<input type="text" placeholder="search" id="name">