Got a feeling this should be simple
I've got some html like this (I don't have control over the html)
<div class="something" data-spec="['thing','another-thing','one-more-thing']">Stuff</div>
I'm trying to read in the data-spec as an array without having to break it down into a string, splitting it up and then push the values into an array.
If I do this:
let elem = $('.something')
let attr = elem[0].attributes['data-spec']
console.log(attr)
It returns:
data-spec="['thing','another-thing','one-more-thing']"
Is there a way to read data-spec as an array object?
Thanks.
I'd otherwise say JSON.parse() it, but since those are single quotes, you can't directly do that.
The horrible option is eval(), but I think a happy middle ground (which could break if there are other quotes in the string) is
const attrString = elem[0].attributes['data-spec'];
// replace single quotes with double quotes for JSON parsing
const attr = JSON.parse(attrString.replace(/'/g, '"'));
Try replacing all single quotes with double quotes and then use JSON.parse
const dataSpec="['thing','another-thing','one-more-thing']"
JSON.parse(dataSpec.replace(/'/g, '"'))
const dataSpec = "['thing','another-thing','one-more-thing']"
const array = JSON.parse(dataSpec.replace(/'/g, '"'))
console.log(array);
Not sure if you can directly do what you want, but as a workaround you can use a regex to extract everything between quote, example :
var test = "data-spec=\"['thing','another-thing','one-more-thing']\"";
var result = test.match(/(?<=\').*(?=\')/);
console.log(result);
//will log : Array [ "thing','another-thing','one-more-thing" ]
Note: maybe you'll have to JSON.stringify(elem[0].attributes['data-spec']) to have the same string "test" that I have in my example