简体   繁体   中英

IndexOf, Search and Contains can't seem to find substring in a bigger string

I have a bot that retrieves smartphones and their prices online. It gets a full description of it and then searches for the device's name like this:

let devices = ['Xperia XA Ultra',
               'iPhone 6  Apple Plus',
               'iPhone 7 Apple Plus Red',
               'LG K9',];

    function recuperarAparelho(fullDescription){
    for(let device of devices){         
        //search for the substring here
    }
    return fullDescription;
}

99% of the time, the search works. But there's one in particular that i can't seem to make it work:

let fullDesc = 'Smartphone LG K9 Preto 16GB, Android 7.0, Dual Chip, TV Digital, Tela 5.0"HD, Câmera 8MP, Processador Quad Core 1.3 Ghz e 2GB de RAM - LMX210BMW 16GB'

The search should've return 'LG K9', but i've tried indexOf(), search() and contains(), but none of them worked. What am i missing here?

Use .includes() Read more about .includes() here

indexOf also works so not sure why it didn't for you - see snippet below

 let fullDesc = 'Smartphone LG K9 Preto 16GB, Android 7.0, Dual Chip, TV Digital, Tela 5.0"HD, Câmera 8MP, Processador Quad Core 1.3 Ghz e 2GB de RAM - LMX210BMW 16GB'; console.log(fullDesc.includes('LG K9')); console.log(!!fullDesc.indexOf('LG K9')); /* double bang to make it boolean */ 

let devices = ['Xperia XA Ultra',
               'iPhone 6  Apple Plus',
               'iPhone 7 Apple Plus Red',
               'LG K9',];

function recuperarAparelho(fullDescription){
for(let device of devices){         
   if(fullDescription.includes(device)) {
       return device;
    }
}
return fullDescription;
}

I found what was wrong with my code. One of the strings had extra white spaces. So here's what i did:

        if(completo.toLowerCase().trim().includes(aparelho.toLowerCase().trim())){
            return aparelho;
        }

And it worked. Thank you for the answers @Sruthi Varghese and @Darren Sweeney. I can't believe i lost so much time because of white spaces...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM