[英]get string from object text using regex
I have some HTML that contain this script我有一些包含此脚本的 HTML
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-117747539-1', {
'custom_map': {
'dimension1': 'novel',
'dimension2': 'chapter',
'dimension5': 'novel_id',
'dimension6': 'chapter_id'
}
});
// Sends the custom dimension to Google Analytics.
gtag('event', 'novel_dimension', {
'novel': 'I'm The Most Evil Support Class【Talker】And I'll Subdue The Strongest Clan In The World',
'chapter': 'Chapter: 002',
'novel_id': '198',
'chapter_id': '7756'
});
I want to get the data novel_id and chapter_id from the object above using regex.我想使用正则表达式从上面的对象中获取数据 Novel_id 和 Chapter_id。
Is that possible?那可能吗?
If you REALLY have a string you can do this better than using a regex如果你真的有一个字符串,你可以比使用正则表达式做得更好
const str = `window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-117747539-1', { 'custom_map': { 'dimension1': 'novel', 'dimension2': 'chapter', 'dimension5': 'novel_id', 'dimension6': 'chapter_id' } }); // Sends the custom dimension to Google Analytics. gtag('event', 'novel_dimension', { 'novel': 'I'm The Most Evil Support Class【Talker】And I'll Subdue The Strongest Clan In The World', 'chapter': 'Chapter: 002', 'novel_id': '198', 'chapter_id': '7756' });` const script = document.createElement("script"); script.textContent=str; document.querySelector("head").appendChild(script) const dim = window.dataLayer[2][2]; // or recursively find object containing key===novel console.log(dim.novel_id,dim.chapter)
If actually an html page with a script then just如果实际上是带有脚本的 html 页面,则只需
window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-117747539-1', { 'custom_map': { 'dimension1': 'novel', 'dimension2': 'chapter', 'dimension5': 'novel_id', 'dimension6': 'chapter_id' } }); // Sends the custom dimension to Google Analytics. gtag('event', 'novel_dimension', { 'novel': 'I'm The Most Evil Support Class【Talker】And I'll Subdue The Strongest Clan In The World', 'chapter': 'Chapter: 002', 'novel_id': '198', 'chapter_id': '7756' }); const dim = window.dataLayer[2][2]; // or recursively find object containing key===novel console.log(dim.novel_id, dim.chapter)
Ok i was able to solv it this way instead好的,我能够以这种方式解决它
var novRegex = /.*?novel_id'\s?:\s?'([\w\s]+)'/i
var chapRegex = /.*?chapter_id'\s?:\s?'([\w\s]+)'/i
var x1 = undefined;
var x2 = undefined;
var html = dom.head.innerText;
x1 = html.match(novRegex)[1]
x2 = html.match(chapRegex)[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.