JS/如何通过名字和姓氏输入进行搜索,但如果我在名字后键入 space 也可以工作

JS/ How to search with input by firstname and lastname but also work if i type space after firstname

let input = document.getElementById('searchInput')
let searchField = document.getElementById('searchField')

input.addEventListener('keyup', (e) => {
    const string = e.target.value
const filteredUsers = users.filter((user) => {
if (string != '') {
if (user.name.first.toLowerCase().includes(string) || user.name.last.toLowerCase().includes(string)) {
 return user
 } else {
            searchField.innerHTML = ''
        }
    } else {
        searchField.innerHTML = ''
    }
})
filteredUsers.map(user => {
    personImg = user.picture.thumbnail
    person = user.name.first + ' ' + user.name.last
    searchField.innerHTML += `<li class="list-group-item"><img src='${personImg}'>${person}</li>`

})})

我已经设法编写了一个搜索功能,其中 returns 获取了用户图片、名字和姓氏。搜索是按名字和姓氏进行的。但是,在输入名字后,如果我显示了多个选项,如果我按 space 输入我选择的姓氏,它就会中断。我如何实现它才能工作?

替换为:

const string = e.target.value
if (user.name.first.toLowerCase().includes(string) || user.name.last.toLowerCase().includes(string)) {

有了这个:

const q1 = e.target.value.split(' ')[0]
const q2 = e.target.value.split(' ')[1]
if (user.name.first.toLowerCase().includes(q1) && (!q2 || user.name.last.toLowerCase().includes(q2))) {}

这样,它将 John Doe 拆分为 JohnDoe,并在名字中搜索 John,在姓氏中搜索 Doe。 (!q2 || 适用于搜索查询仅包含名字的情况。)

这里是更完整的答案:

// mock user data
let user = {name: {first: 'John', last: 'Doe'}}
// mock event
let e = {target: {value: 'John D'}}
// searched queries
const q1 = e.target.value.toLowerCase().split(' ')[0]
const q2 = e.target.value.toLowerCase().split(' ')[1]
let matched = false;
const first = user.name.first.toLowerCase();
const last = user.name.last.toLowerCase();
if(!q2){
  // when we entered just `John`,
  // then we should match all first names or last names containing `John`
  if(first.includes(q1) || last.includes(q1)) matched = true;
}else{
  // when we entered just `John D`, first name should match `John` and last name should match `D`.
  if(first.includes(q1) && last.includes(q2)) matched = true;
}
if (matched) {}

此外,如果名称可能有更多块(如:John Doe Smith),您可以将搜索字符串拆分成块,并在名称内搜索它们,并对结果进行排序。像 :

let foundUser = undefined;
e.target.value.split(' ').forEach(q => {
  if (user.name.first.toLowerCase().includes(q) || 
      user.name.last.toLowerCase().includes(q)) {
        foundUser = user;
  }
})
if(foundUser){...}else{...}