if variable contains

124,826

Solution 1

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

Solution 2

You can use a regex:

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

Solution 3

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
}

Solution 4

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

Solution 5

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.

Share:
124,826
Admin
Author by

Admin

Updated on October 03, 2020

Comments

  • Admin
    Admin over 3 years

    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.

  • Alex K.
    Alex K. over 11 years
    +1 for nice and easy case insensitivity
  • clentfort
    clentfort over 11 years
    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.