Samantha J T Star
Samantha J T Star

Reputation: 32828

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

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?

Upvotes: 1

Views: 3568

Answers (4)

RiaD
RiaD

Reputation: 47640

if(idCity.substr(0,2)=='AB'){
}

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

if(idCity.substr(0,start.length)==start){
}

Upvotes: 2

Joachim Isaksson
Joachim Isaksson

Reputation: 180987

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

Upvotes: 2

mohdajami
mohdajami

Reputation: 9690

idCity = 'AB767 something';

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

Upvotes: 0

Marc B
Marc B

Reputation: 360762

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

Upvotes: 3

Related Questions