Two tips for quick migration from analytics.js to gtag.js
Google has instructions on how to migrate from analytics.js
to gtag.js
with the steps being straight-forward.
While doing this, two things helped me:
1. Set up a GAID
constant
So, the tracking code would look like this:
This helps use it in code that manually triggers pageview tracking or ecomm.
For example, pageview tracking in code can now be triggered by:
gtag('config', GAID);
2. Use regular expressions to upgrade old events
First, replace this:
ga\(['"]send['"], ['"]event['"], ['"](.+)['"], (.+)\)
with this:
gtag('event', '$1', {event_category: '$1', event_label: $2})
And then
ga\(['"]send['"], ['"]event['"], ['"](.+)['"]\)
with this:
gtag('event', '$1', {event_category: '$1'})
It’s important to do it in order so that labels and categories can be picked up correctly.