2012-10-22 80 views
8

可能重复:
JavaScript: string contains如果变量包含

我有一个邮政编码变量,要使用JS时,邮政编码改变添加位置信息到一个不同的变量/输入。例如,如果输入ST6,我想要输入Stoke North。

我需要做一个if语句来遍历例如

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

等等

我会如何呢?它不检查'代码'是否等于一个值,但如果它包含一个值,我认为这是我的问题。

+0

这里是检查字符串是否在字符串中的最常用方法的基准:http://jsben.ch/#/o6KmH – EscapeNetscape

回答

27

你可能想indexOf

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

它检查是否contains是在string变量code任何地方。这要求code是一个字符串。如果您希望此解决方案不区分大小写,则必须将案例更改为与String.toLowerCase()String.toUpperCase()一致。

你也可以用switch声明的工作就像

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

好东西,谢谢。 –

8

您可以使用正则表达式:

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

+1,用于方便,不区分大小写 –

1

最快的方法来检查,如果字符串包含另一个字符串是使用​​:

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

如果未找到字符串,indexOf返回“-1”。如果字符串以'ST1'开始,它将返回'0'。这个答案是错误的。你检查'代码'是否以'ST1'开始,而不是'代码'中是否包含*。 – clentfort

+0

@clentfort谢谢,脑屁。 – jbabey

2

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

0

如果你有很多这些来检查你可能想存储的映射列表,只是循环,而不是一堆o f if/else语句。例如:

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

这样您可以轻松地添加更多的代码/位置映射。如果你想处理多个位置,你可以在函数中建立一个位置数组,而不是仅仅返回你找到的第一个位置。

相关问题