javascript - Jquery check if array contains substring -


i trying check if array regions contains part of string users submit. in essence, jquery script should check if city user included in address 1 of cities in regions array.

for example, when user enters examplestreet 24 city1 , city1 in regions array, should display price of €40, else should show €2/km.

i have following code:

var regions = ["city1", "city2", "city3"]; var str = $("#addressfield").val(); var address = str.tolowercase(); var key, value, result; (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 working fine when string city without street or other characters, should work if enters full address. need change code searches array regions part of string address.

you can use regexp find 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));


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -