const search = document.querySelector('#search');
const matchList = document.querySelector('#match-list');
let studentsDetails;
const searchStudents = async searchText => {
const res = await fetch('https://www.hatchways.io/api/assessment/students');
const fetchStudents = await res.json();
const studentsDetails = fetchStudents.students;
console.log(studentsDetails);
var content = [];
for (var i = 0; i < studentsDetails.length; i++) {
content.push(studentsDetails[i].firstName);
}
console.log(content);
// Match to current text input
let matches = content.filter(student => {
const regex = new RegExp(`^${searchText}`, 'gi');
return content.firstName.match(regex) || content.lastName.match(regex);
});
console.log(matches);
}
search.addEventListener('input', () => searchStudents(search.value));
Is your question about the RegEx? Because your function seems to be working correctly, as far as getting the API response is concerned.
1 Like
I want to filter a data when typing in search bar.
Your regex search is incorrect.
First, you want to use student
to run .match()
on, instead of content.firstName.match
, because student
will be the current string being iterated upon.
And next, I don’t think you’ve pushed last names onto content
, so this won’t work anyway -
content.lastName.match(regex)
.
If I change your code to -
let matches = content.filter(student => {
const regex = new RegExp(`^${searchText}`, 'gi');
return student.match(regex);
});
console.log(matches);
And call the function with searchStudents('Mureil')
, I get - ["Mureil"]
Yes it working know but just for the first name I want it also by last name and get all data about this student. because it just give me his name.