Skip to content
Advertisement

Conditional check in JavaScript not working

I am trying below code but it’s not working as expected. I wanted to check if the cell Value has India or UnitedStatedofAmerica or Germany or Switzerland then go inside and if it’s undefined, null or blank, or it doesn’t contain the text location then go to else and set the value to ROW, But its not working.

So each time it give me results ROW even if cell have India or UnitedStatedofAmerica and when its null it goes inside the true condition and throw error for split as cell.Value is null

3 Example cell.Value

“Lorem Ipsum is simply dummy text of the printing and typesetting;Location India, Mumbai;Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of the printing and typesetting”

“Location India;Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of the printing and typesetting;Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of the printing and typesetting”

“Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is simply dummy text of the printing and typesetting;Lorem Ipsum is simply dummy text of the printing and typesettingLorem Ipsum is;Location United Stated of America; simply dummy text of the printing and typesetting”

if (cell.Value.split('Location')[1].split(',')[0].replace(/s/g, "") === "India" || cell.Value.split('Location')[1].split(',')[0].replace(/s/g, "") === "Germany" || cell.Value.split('Location')[1].split(',')[0].replace(/s/g, "") === "UnitedStatesofAmerica" || cell.Value.split('Location')[1].split(',')[0].replace(/s/g, "") === "Switzerland" || cell.Value !== 'undefined' || cell.Value !== null || cell.Value !== "" || cell.Value.toLowerCase().indexOf("Location") !== -1) {
  persona.country = cell.Value.split('Location')[1].split(',')[0].replace(/s/g, "");
} else {
  persona.country = "ROW"
}

Advertisement

Answer

You could simplify some parts with some variables and an array of wanted countries.

const
    value = cell.Value || '',
    country = value.split('Location')?.[1]?.split(',')[0].replace(/s/g, ""),
    countries = ["India", "Germany", "UnitedStatesofAmerica", "Switzerland"];

persona.country = countries.includes(country)
    ? country
    : "ROW";
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement