Petra
Petra

Reputation: 575

jQuery: Get value from comma seperated options list

I feel its very simple, but on mondays it's really hard. ^^

I've some HTML like this (it's fix - can't change anything here):

<a class="boxed" href="#foo" rel="type: 'box', image: '/media/images/theimage.jpg', param3: 'title here'">bar</a>

To get the value from the rel is easy with var $(this).attr('rel'); but how do I get the value for image or title inside this list? Sure split will work, but I think there's a better way...

Upvotes: 0

Views: 90

Answers (3)

Venkata Krishna
Venkata Krishna

Reputation: 15112

var rel = $('.boxed').attr('rel');
var arr = rel.split(',');
$.each(arr, function() {
    alert(this.split(':').pop());
});

JSFIDDLE DEMO

Upvotes: 1

Populus
Populus

Reputation: 7680

Split works fine here... if you want an associative array:

var str = "type: 'box', image: '/media/images/theimage.jpg', param3: 'title here'";
var arr = str.split(',');
var answer = {};

for (var i = 0, len = arr.length; i < len; i++) {
    var values = arr[i].split(':');
    answer[values[0].trim()] = values[1].trim();
}

But the regex solution by @epascarello is better than this.

Upvotes: 0

epascarello
epascarello

Reputation: 207537

There are a bunch of ways to do it, here is one that just uses a regular expression to match the groups.

var str = "type: 'box', image: '/media/images/theimage.jpg', param3: 'title here'";
var re = /\s?([^:]*):\s'([^']*)',?/;
var result;
var prop = {};
while ((result = re.exec(str)) !== null) {
    prop[result[1]] = result[2];
    str = str.replace(re,"");
}
console.log(prop);

Another way making it a JSON valid string and using parse

var str = "type: 'box', image: '/media/images/theimage.jpg', param3: 'title here'";
var re1 = /(^|,\s)([^:]*)/g;
var re2 = /'/g;
var json = "{" + str.replace(re1,'$1"$2"').replace(re2,'"') + "}";
var prop = JSON.parse(json);
console.log(prop);

Upvotes: 0

Related Questions