Mitya Ustinov
Mitya Ustinov

Reputation: 903

Find certain data in string with JavaScript

I have a string in JavaScript application:

const articleBody = "<div class=\"article\" data-id=\"123456\" data-title=\"Some long article title\">Article content goes here.</div>"

There is no way for me to set this as HTML and then get data- values as I would normally do, so I need to "extract" data- attribute values from string. In the end I need to have something like that:

const id="123456"
const title="Some long article title"

How would I do that with JavaScript?

Thank you!

Upvotes: 0

Views: 62

Answers (3)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

Take up the string and try converting it into HTML template using document.createElement..

const template = document.createElement('div');
template.innerHTML = articleBody;

Then you can use getAttribute method to retrieve the value of the attribute you wish to fetch..

const id = template.querySelector('.article').getAttribute("data-id");
const title = template.querySelector('.article').getAttribute("data-title");

And the expected solution can be formed as,

const articleBody = "<div class=\"article\" data-id=\"123456\" data-title=\"Some long article title\">Article content goes here.</div>"


const template = document.createElement('div');
template.innerHTML = articleBody;

const id = template.querySelector('.article').getAttribute("data-id");
const title = template.querySelector('.article').getAttribute("data-title");

console.log(id, title);

Upvotes: 1

Constantin Trepadus
Constantin Trepadus

Reputation: 503

Here you can use this script here, it will split your string to array, get the attribute, get numbers from it with regex and parse it to int:

var str = "<div class=\"article\" data-id=\"1234576\" data-title=\"Some long article title\">Article content goes here.</div>";
var attribute = str.split(" ").filter(item =>{
  return item.includes("data-id");
});
var result = attribute.toString().replace( /^\D+/g, '').match(/\d+/)[0];
console.log(parseInt(result));

Upvotes: 0

igg
igg

Reputation: 2250

You can use template.

const articleBody = "<div class=\"article\" data-id=\"123456\" data-title=\"Some long article title\">Article content goes here.</div>"

const template = document.createElement('template');
template.innerHTML = articleBody;
const article = template.content.children[0];

const {
  id,
  title
} = article.dataset;

console.log(id, title);

Upvotes: 0

Related Questions