54

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.

1
  • Here a benchmark for the most common ways to check if a string is in a string: jsben.ch/#/o6KmH Commented Oct 31, 2016 at 17:06

5 Answers 5

61

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;        
    }​
Sign up to request clarification or add additional context in comments.

Comments

15

You can use a regex:

if (/ST1/i.test(code))

1 Comment

+1 for nice and easy case insensitivity
7

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 Comment

indexOf returns -1 if the string is not found. It will return 0 if the string start with ST1. This answer is wrong. You check if code starts with ST1 not if it is anywhere contained in code.
4

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

Comments

1

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.

Comments