thednp
thednp

Reputation: 4479

Javascript: how to extract string from attribute via Regexp

How can I extract the string from a certain data attribute via regexp.

<button data-loading-text="Some text on loading" data-toggle="button">Button</button>
<button data-finished-text="Some text on finished" data-toggle="button">Button</button>

And my javascript is

var Buttons = document.querySelectorAll([data-toggle="button"]);
[].forEach.call(Buttons, function (item) {
    var data = item.getAttribute('data-'+INEEDTHIS+'-text')
    var option = INEEDTHIS
    return new Button(item,option);
})

Upvotes: 0

Views: 101

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use the Element.attributes property:

var attrs = item.attributes;
for(var i = attrs.length - 1; i >= 0; i--) {
    var m = attrs[i].name.match(/^data-(.*)-text$/);
    if (m) {
        var option = m[1];
        // do something
    }
}

Upvotes: 1

jmgross
jmgross

Reputation: 2336

You can use the .attr() method of jQuery

Upvotes: 0

Related Questions