简体   繁体   中英

How to extract a part of a value inside an attribute

I have many hyperlinks with a onclick function which have differents values on this way:

<a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'bikes'});">bikes whatever</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'motorcycles'});">another motor</a>

Now when this element is clicked I need to get the values of that array, example: "cars", or "bikes" or "motorcycles".

Don't suggest to get them from the Utils.decideOffer function because I need to get them without edit that file/function. This is how I intend to extract it.

$('a').click(function() {
    onclickValue = $(this).attr('onclick');
    if (onclickValue.length) {
      var optionSelectedValue = ??? ;
    }
});

I was thinking on use Regex so can you please help me on the Regex to use on this case?, or if you have another good idea to achieve this it is also welcome!

Try split() like :

$('a').click(function() {
    onclickValue = $(this).attr('onclick');
    if (onclickValue.length) {
      var optionSelectedValue = onclickValue.split(":")[1].split("}")[0];
    }
});

it will return the 'cars' or 'bikes' or 'motorcycles' including the quotes

See JSFIDDLE

... or to get the value without quotes as suggested :

optionSelectedValue = onclickValue.split(":")[1].split("}")[0].split("'")[1];

See updated JSFIDDLE

$('a').click(function() {
    onclickValue = $(this).attr('onclick');
    if (onclickValue.length) {
        var re = /(?!: ')+(\w)+(?='})/;
var found = onclickValue.match(re);
      var optionSelectedValue = found[0] ;
        alert(optionSelectedValue);
    }
});

Demo: http://jsfiddle.net/wpjh1ma7/

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