Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Reading a html attribute as an array using Javascript / Jquery

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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, '"')); 
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!