2

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">
shaalan
  • 21
  • 1

1 Answers1

0

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">
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • i think u did not understand what i mean :) – shaalan Mar 10 '22 at 03:18
  • i do not take about the * and how to implement it i need to find strings that conatin any part of this string like if i type ((a*e)) i need thr result to be this ((apple , pen)) – shaalan Mar 10 '22 at 03:20
  • since both of them contain ((p AND e)) no mater the order and where these letters are – shaalan Mar 10 '22 at 03:21