I use following way to fetch the value of gtag if it already exists in the code:
<script>
const regex = /googletagmanager\.com\/gtag\/js\?id=([^\s'"]+)/gi;
const scriptTags = document.querySelectorAll('script');
let trackingID = '';
scriptTags.forEach(script => {
const src = script.getAttribute('src');
if (src && src.includes('googletagmanager.com/gtag/js')) {
const match = regex.exec(src);
if (match && match.length > 1) {
trackingID = match[1];
}
}
});
</script>
Now I want the trackingID to be printed in the following script if it exists else print the code value that exists
<script async src="<?php echo ( $local_analytics_file ?? 'https://www.googletagmanager.com/gtag/js?id=' ) . '?' . esc_html( $UA_CODE ); ?>"></script>
Need something like
<script async src="<?php echo ( $local_analytics_file ?? 'https://www.googletagmanager.com/gtag/js?id=+if(trackingID) trackingID' ) . '?' . esc_html( $UA_CODE ); ?>"></script>
And similarly in following
<script>
console.log('Google Analytics Tracking ID:', trackingID);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
const configuration = JSON.parse( '<?php echo $configuration; ?>' );
const gaID = '<?php echo esc_html( $UA_CODE ); ?>'; // I want trackingID to be printed if available else print the $UA_CODE
</script>