user1464139
user1464139

Reputation:

Is there a way in javascript for me to check if an element id matches a string?

I coded the following:

var btnID = $link.attr('id');
var cityNumber = btnID.substring(4);
$('#cityLegend-1').html('City ' + cityNumber);

However I need this to do the last two lines only if the btnID starts with "btn-". Is there a way I could check this happens and then if the id is something like "btn-1" or "btn-999" then do the last two lines?

Upvotes: 0

Views: 1050

Answers (5)

Adil
Adil

Reputation: 148150

You can use .eq(-index), passing index counting backwards from the last element in the set.

Live Demo

$('[id^=cityLegend-]').eq(-1) for last
$('[id^=cityLegend-]').eq(-2) for second last

Edit, you can use split instead of substring to get the number after hyphen.

var btnID = $link.attr('id');
var cityNumber = btnID.spilt('-')[1];

Upvotes: 6

rosshamish
rosshamish

Reputation: 1160

/** .substring() does a length check internally **/
if (btnId.substring(0,3) == "btn") { 
    // do stuff
}

Upvotes: 3

Steve
Steve

Reputation: 8640

I am not sure how flexible your code is, but I usually approach similar set-ups a little differently. I would do the following (which may or may not be possible for you):

  • Instead of searching for an element that starts with a certain string in the id, why not use a specific class for all the buttons you might be interested in. That way, you can use a jQuery selector like $('.mySpecialBtn')
  • Instead of attaching an integer at the end of an id and then parsing it out, why not just use a data attribute to contain the id, i.e. data-my-button-id="1"?

So to put both parts together, you could have something like this:

HTML:

<button class="mySpecialBtn" data-my-button-id="1">Button 1</button>
<button class="mySpecialBtn" data-my-button-id="2">Button 2</button>
<button class="mySpecialBtn" data-my-button-id="3">Button 3</button>

JS:

$('mySpecialBtn').each(function() {
    var btnId = $(this).data("my-button-id"));
    // do something with btnId
});

Upvotes: 0

aug
aug

Reputation: 11714

You could just a the .match() method and with a regex that checks if the starting 'id' starts with btn.

if (btnID.match(/^btn/g)) {
     //do stuff
}

Upvotes: 0

Yohanes Gultom
Yohanes Gultom

Reputation: 3842

So many options. This too will work :

var btnID = $(link).attr('id');
if(btnID.substr(0,4) == 'btn-'){
    var cityNumber = btnID.substring(4);
    $('#cityLegend-1').text('City ' + cityNumber);
}else{
    $('#cityLegend-1').text('City ' + btnID);
}

Upvotes: 1

Related Questions