最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I check if the contents of a variable start with something? - Stack Overflow

programmeradmin2浏览0评论

I would like to do something like this:

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

In other words. I want to check that idCity starts with the string "AB". How can I do this in Javascript?

I would like to do something like this:

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

In other words. I want to check that idCity starts with the string "AB". How can I do this in Javascript?

Share Improve this question asked Jan 8, 2012 at 8:06 Samantha J T StarSamantha J T Star 33k89 gold badges257 silver badges441 bronze badges 3
  • See stackoverflow./questions/646628/javascript-startswith – Joachim Isaksson Commented Jan 8, 2012 at 8:13
  • possible duplicate of javascript - check if string begins with something? – Felix Kling Commented Jan 8, 2012 at 9:10
  • How about reading through the list of string manipulation methods until you find one that seems to do the trick? – nnnnnn Commented Jan 8, 2012 at 9:20
Add a ment  | 

4 Answers 4

Reset to default 3
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'){
}

If 'AB' is not constant string, you may use

if(idCity.substr(0,start.length)==start){
}
idCity = 'AB767 something';

function startWith(searchString){
    if (idCity.indexOf(searchString) == 0){
         return true;
    }
    return false;
}
发布评论

评论列表(0)

  1. 暂无评论