Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  0] [ 3]  / answers: 1 / hits: 133720  / 12 Years ago, mon, october 22, 2012, 12:00:00

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.


More From » variables

 Answers
360

You might want indexOf



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


It checks if contains is anywhere in the string variable code. This requires code to be a string. If you want this solution to be case-insensitive you have to change the case to all the same with either String.toLowerCase() or String.toUpperCase().



You could also work with a switch statement like



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;
}​

[#82421] Sunday, October 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lamontm

Total Points: 482
Total Questions: 99
Total Answers: 91

Location: Burkina Faso
Member since Thu, Dec 15, 2022
2 Years ago
;