If the variable contains

Possible duplicate:
JavaScript: string contains

I have a zip code variable and you want to use JS to add location to another variable when zip code is changed / entered. So, for example, if ST6 is introduced, I would like to introduce Stoke North.

I somehow need to execute the if statement to run, for example,

if(code contains ST1) { location = stoke central; } else if(code contains ST2) { location = stoke north; } 

etc...

How can i do this? It does not check if the "code" is equal to the value, but if it contains the value, I think this is my problem.

+8
javascript variables if-statement postal-code
source share
5 answers

You may need indexOf

 if (code.indexOf("ST1") >= 0) { ... } else if (code.indexOf("ST2") >= 0) { ... } 

It checks to see if contains somewhere in the string code variable. This requires code be a string. If you want this solution to be case insensitive, you still need to change the case to String.toLowerCase() or String.toUpperCase() .

You can also work with a switch , for example

 switch (true) { case (code.indexOf('ST1') >= 0): document.write('code contains "ST1"'); break; case (code.indexOf('ST2') >= 0): document.write('code contains "ST2"'); break; case (code.indexOf('ST3') >= 0): document.write('code contains "ST3"'); break; }​ 
+27
source share

You can use regex:

 if (/ST1/i.test(code)) 
+8
source share

if (code.indexOf("ST1")>=0) { location = "stoke central"; }

+2
source share

The fastest way to check if a string contains another string is using indexOf :

 if (code.indexOf('ST1') !== -1) { // string code has "ST1" in it } else { // string code does not have "ST1" in it } 
+1
source share

If you have a lot of them, to check that you want to keep the list of mappings and just loop into them, instead of having a bunch of if / else statements. Something like:

 var CODE_TO_LOCATION = { 'ST1': 'stoke central', 'ST2': 'stoke north', // ... }; function getLocation(text) { for (var code in CODE_TO_LOCATION) { if (text.indexOf(code) != -1) { return CODE_TO_LOCATION[code]; } } return null; } 

This way you can easily add additional code / location mappings. And if you want to handle multiple locations, you can simply create an array of locations in the function instead of just returning the first one you find.

0
source share

All Articles