Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda