Possible Duplicate:
JavaScript: string contains
I have a postcode variable and want to use JS to add a location into a different variable when the postcode is changed/entered. So for example if ST6 is entered I would want Stoke North to be entered.
I somehow need to do an if statement to run through e.g.
if(code contains ST1)
{
location = stoke central;
}
else if(code contains ST2)
{
location = stoke north;
}
etc...
How would I go about this? It's not checking if 'code' equals a value but if it contains a value, I think this is my problem.
This question is related to
javascript
variables
if-statement
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
}
If you have a lot of these to check you might want to store a list of the mappings and just loop over that, 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 more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.
if (code.indexOf("ST1")>=0) { location = "stoke central"; }
You can use a regex:
if (/ST1/i.test(code))
Source: Stackoverflow.com