0

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!

Mitya Ustinov
  • 903
  • 3
  • 11
  • 17
  • 2
    "There is no way for me to set this as HTML and then get data- values as I would normally do" Why not? – Heretic Monkey Dec 18 '19 at 13:56
  • Does this answer your question? [Creating a new DOM element from an HTML string using built-in DOM methods or Prototype](https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro) – Heretic Monkey Dec 18 '19 at 15:40

3 Answers3

1

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);
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
0

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);
igg
  • 2,172
  • 3
  • 10
  • 33
0

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