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!

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.