1

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?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • See http://stackoverflow.com/questions/646628/javascript-startswith – Joachim Isaksson Jan 08 '12 at 08:13
  • possible duplicate of [javascript - check if string begins with something?](http://stackoverflow.com/questions/1767246/javascript-check-if-string-begins-with-something) – Felix Kling Jan 08 '12 at 09:10
  • How about reading through the [list of string manipulation methods](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#Methods_unrelated_to_HTML) until you find one that seems to do the trick? – nnnnnn Jan 08 '12 at 09:20

4 Answers4

3
if (idCity.substr(0,2) == 'AB') {
   alert('the string starts with AB');
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
2
if(idCity.substr(0,2)=='AB'){
}

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

if(idCity.substr(0,start.length)==start){
}
RiaD
  • 46,822
  • 11
  • 79
  • 123
2
if(idCity.indexOf('AB') == 0)
{
  alert('the string starts with AB');
}
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0
idCity = 'AB767 something';

function startWith(searchString){
    if (idCity.indexOf(searchString) == 0){
         return true;
    }
    return false;
}
mohdajami
  • 9,604
  • 3
  • 32
  • 53