Javascript 如何搜索匹配的名称

Javascript 如何搜索匹配的名称,javascript,for-loop,web-scraping,puppeteer,Javascript,For Loop,Web Scraping,Puppeteer,“名称”包含从网页抓取后的页面中提取的名称,但我想检查在抓取后找到的名称中是否存在我的搜索名称,使用了includes和indexof,但均无效 try{ for(let name of names){ if(name.includes(find_name)){ console.log("got a match!") await page.goto(name.link) await sleep(5000); } } }catch(e){

“名称”包含从网页抓取后的页面中提取的名称,但我想检查在抓取后找到的名称中是否存在我的搜索名称,使用了includes和indexof,但均无效

try{
  for(let name of names){
    if(name.includes(find_name)){
      console.log("got a match!")
      await page.goto(name.link)
      await sleep(5000);
    }
  }
}catch(e){
  console.log('could not check for match', e);
}

您可以通过多种方式进行搜索,对于简单的字符串搜索,我主要使用两种方式:str.search,就像您的例子一样-

if (name.search(find_name)) {
   console.log("got a match!")
   await page.goto(name.link)
   await sleep(5000);
} 
在上面,若它找到than,它将给你们字符串的位置,若并没有找到than-1

或者你可以像这样进行严格的搜索-

var search = new RegExp(find_name , 'i'); // search term 
let searchedNameList = names.filter(name => search.test(name));
for (let name of searchedNameList) {
   await page.goto(name.link)
   await sleep(5000);
}
上面将为您提供包含您的所有姓名列表
find_name
,您可以像这样在searchedNameList上循环- 您也可以像使用async/await一样使用-

for await (let name of names) {}
跳这个有帮助