我正在使用此脚本,由于我不熟悉JavaScript,因此我想从Google Analytics(分析)脚本“ UA-101203313-3”中获取trackid
更具体地说,我想要这样:const trackid ='UA-101203313-3'。如何找回呢?
你能告诉我怎么做吗?
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-101203313-3"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-101203313-3');
</script>
答案 0 :(得分:1)
所以,听起来您想抓些文字。您可以使用此正则表达式来匹配脚本src
属性
var trackid = text.match(/\?id=(UA-\d+-\d+)/)[1]
这种方式仅在数据是字符串的情况下有效:
const text = `<script async src="https://www.googletagmanager.com/gtag/js?id=UA-101203313-3"><\/script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-101203313-3');
<\/script>`
var trackid = text.match(/\?id=(UA-\d+-\d+)/)[1]
console.log(trackid)
如果数据已经嵌入在页面中,则可以选择脚本标签并以类似的方式获取它:
var trackid = document.getElementById('google-manager').src.match(/\?id=(UA-\d+-\d+)/)[1]
console.log(trackid)
<script id="google-manager" async src="https://www.googletagmanager.com/gtag/js?id=UA-101203313-3"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-101203313-3');
</script>