简体   繁体   中英

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);
})

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
    }
}

您可以使用jQuery的.attr()方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM