如何检查变量的内容是否以某个内容开头

How can I check if the contents of a variable start with something?

本文关键字:是否 开头 何检查 检查 变量      更新时间:2023-09-26

我想做这样的事情:

if (idCity == 'AB*') {
   //  do something
}

换句话说。我想检查idCity是否以字符串"AB"开头。我如何在Javascript中做到这一点?

if (idCity.substr(0,2) == 'AB') {
   alert('the string starts with AB');
}
if(idCity.indexOf('AB') == 0)
{
  alert('the string starts with AB');
}
if(idCity.substr(0,2)=='AB'){
}

如果"AB"不是常量字符串,则可以使用

if(idCity.substr(0,start.length)==start){
}
idCity = 'AB767 something';
function startWith(searchString){
    if (idCity.indexOf(searchString) == 0){
         return true;
    }
    return false;
}