Quiero agregar la función de búsqueda. Necesito buscar cualquier documento por letra inicial.
Supongamos que tenemos algún documento como-
Apple Industry Samsung Industry Xioami Industry Ahua Industry Sumatech IndustryCuando el usuario busca un entonces debería dar el resultado que comienza con un me gusta-
Ahua Industry Apple IndustryPuede ver el resultado mostrado en orden alfabético
Ya he creado una expresión regular como esta-
{ Industry: { '$regex': 'a', '$options': 'i' } } Pero muestra todo el contenido que contiene a archivo .
Me gusta-
Muestra cada contenido porque todo el contenido contiene a archivo .
Como puedo solucionar eso. Alguien puede ayudarme.
Debe agregar el modificador startWith a su expresión regular. No estoy seguro de cómo este objeto se convierte a la expresión regular, pero aquí tienes:
{ Industry: { '$regex': '^a.*', '$options': 'i' } } function matchText(query) { const text = ['Apple Industry', 'Samsung Industry', 'Xioami Industry', 'Ahua Industry', 'Sumatech Industry' ]; const regex = new RegExp(`^${query}.*`, 'i'); text.forEach((item) => console.log(item.match(regex))); } matchText('a'); matchText('ap');