Search code examples
javascriptstringgoogle-chrome-extensionstring-comparison

Chrome extension: String comparison in JavaScript not working


I am trying to compare two strings using JavaScript, and I am honestly stumped as to why this is not working for me. I've tried using ==, ===, localeCompare(), adding spaces, converting it to lowercase, and nothing is working! Here is my code (from my content script)

var longBrand = byline.innerHTML;
var brand = longBrand.substring(7);
console.log(brand);

if(brand){
    console.log("It can read inside this statement");
    var lowerBrand = brand.toLowerCase();
    console.log(lowerBrand);
    if(lowerBrand === "nike" || lowerBrand === " nike" || lowerBrand === "  nike"){
        console.log("testing");
    }
}

The variable brand comes from a substring of longBrand, which is taken from a webpage. The console shows everything is logged except for the last console.log("testing"); and I can't figure out why that is. Console looks like this:

Nike
It can read inside this statement
nike

I've even double checked that typeof brand is a string. I don't know what's going wrong here! Any help would be greatly appreciated!


Solution

  • Well, it works good here. Maybe your variable brand isn't "Nike". Try to do:
    brand = brand.trim();
    to remove white spaces.

    // var longBrand = byline.innerHTML;
    // var brand = longBrand.substring(7);
    const brand = "Nike"
    
    if(brand){
        console.log("It can read inside this statement");
        const lowerBrand = brand.toLowerCase();
        console.log(lowerBrand);
        if(lowerBrand === "nike" || lowerBrand === " nike" || lowerBrand === "  nike"){
            console.log("testing");
        }
    }