0

I am trying to check if my array regions contains part of a string that users submit. In essence, this jquery script should check if the city that a user included in their address is one of the cities in the regions array.

For example, when a user enters Examplestreet 24 City1 and City1 is in the regions array, it should display a price of €40, else it should show €2/km.

I have the following code:

var regions = ["city1", "city2", "city3"];
var str = $("#addressField").val();
var address = str.toLowerCase();
var key, value, result;
for (key in regions) {
    if (regions.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
        value = regions[key];
        if (value.substring() === address) {
            $("#deliveryPrice").text("€40");
        }
        else {
            $("#deliveryPrice").text("€2/km");
        }
    }
}

This code is working fine when the string is just the city without the street or other characters, but it should also work if someone enters their full address. So I need to change my code so it searches the array regions for any part of the string address.

2 Answers 2

2

You can use regexp to find the right price:

var regions = ["city1", "city2", "city3"];
var address = "example address 42-200 City1 Poland";
var address2 = "city3";
var address3 = "city6";

function priceForAddress(address, regions) {
  var city = regions.find(function (region) {
    var reg = new RegExp(region, 'i');
    return address.match(reg) !== null;
  });
  
  if (city) {
    return '20$';
  } else {
    return '4$/km';
  }
}

console.log(priceForAddress(address, regions));
console.log(priceForAddress(address2, regions));
console.log(priceForAddress(address3, regions));

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect and solved my problem! Thanks a lot!
0

You should just find if one of the cities is inside the string using indexOf

function test()
{
  var regions = ["city1", "city2", "city3"];
  var str = "Examplestreet 24 City1";
  var address = str.toLowerCase();
  var value, result;
  for (value of regions) {
      result = str.toLowerCase().indexOf(value);
      console.log(result); 
      if (result !== -1)
      {
        console.log("$40");
        return;
      }
      else
      {
        console.log("$2/km");
        return;
      }
  }
}

test();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.