...">

How to get part of attribute value using jquery

I have an attribute value like:

<div id = "2fComponents-2fPromotion-2f" class = "promotion">

Now I want to get only part of it, let's say Promotionits value 2f, how can I get this using jquery? Do we have a built-in function for this?

+3
source share
4 answers

Here you can use regex:

var attId = $(".promotion").attr("id");

// Perform a match on "Promotion-" followed by 2 characters in the range [0-9a-f]
var match = attId.match(/Promotion-([0-9a-f]{2})/);

alert(match[1]); // match[0] contains "Promotion-2f", match[1] contains "2f"

This assumes that "value" Promotionis a hexadecimal value, and the characters [af] will always be lowercase. It is also easily configurable to match other values, for example, if I change the regex to /component-([0-9a-f]{2})/, there will be a matching array ["component-3a", "3a"].

. , ( /Promotion-[0-9a-f]{2}/). (, ) , , (Promotion) 1 ([0-9a-f]{2}) 2.

match MSDN

+3
var id = $("div.promotion").attr("id");
var index = id.indexOf("Promotion");
var promotion = '';

// if the word 'Promotion' is present
if(index !== -1) {

    // extract it up to the end of the string
    promotion = id.substring(index);

    // split it at the hyphen '-', the second offset is the promotion code
    alert(promotion.split('-')[1]);
} else {
    alert("promotion code not found");
}
+1

id :

var id= $('div.promotion').attr('id');

, , .

id, , :

<div class="promotion" zone="3a-2f-2f" home="2f"></div>

:

var zone= $('div.promotion').attr('zone');
var home= $('div.promotion').attr('home');

jQuery.data()

0
 $(function () {

        var promotion = $('.promotion').attr('id').match(/Promotion-([0-9a-f]{2})/);

        if (promotion.length > 0) {

            alert(promotion[1]);
        }

        else {

            return false;
        }

    });
0
source

Source: https://habr.com/ru/post/1744133/


All Articles