Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda