我在 JavaScript 应用程序中有一个字符串:
const articleBody = "<div class=\"article\" data-id=\"123456\" data-title=\"Some long article title\">Article content goes here.</div>"
我无法将其设置为 HTML,然后像通常那样获取数据值,因此我需要从字符串中“提取”数据属性值。最后我需要有这样的东西:
const id="123456"
const title="Some long article title"
我如何使用 JavaScript 做到这一点?
谢谢!
最佳答案
获取字符串并尝试使用 document.createElement
将其转换为 HTML 模板..
const template = document.createElement('div');
template.innerHTML = articleBody;
然后你可以使用getAttribute
方法来检索你想要获取的attribute
的值..
const id = template.querySelector('.article').getAttribute("data-id");
const title = template.querySelector('.article').getAttribute("data-title");
预期的解决方案可以形成为,
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);
关于javascript - 使用 JavaScript 查找字符串中的某些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59393527/