Possible Duplicate:
JavaScript: string contains
我有一个邮政编码变量,并且希望在更改/输入邮政编码时使用 JS 将位置添加到不同的变量中。例如,如果输入 ST6,我希望输入斯托克北。
我不知何故需要执行一个 if 语句来运行,例如
if(code contains ST1)
{
location = stoke central;
}
else if(code contains ST2)
{
location = stoke north;
}
等等...
我该如何解决这个问题?它不检查“code”是否等于一个值,但如果它包含一个值,我认为这是我的问题。
最佳答案
您可能需要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;
}
关于javascript - 如果变量包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012666/