Extract part of URL with Google tag manager

2019-03-03 13:56发布

问题:

So i have this url "https://www.site.be/pand/titel-van-het-pand-t8500-17082-4" and i have to extract the reference number at the back of the url. In this example "t8500-17082-4" with GTM to put into a custom dimension like this:

var dimensionValue = 'REFERENCE_CODE_HERE';
ga('set', 'dimension1', dimensionValue);

The reference codes at the eind of the url could start with either -t8... or t9...

回答1:

In GTM go to "Variables" -> "NEW" -> "Custom JavaScript" and type:

function(){

  var myRegexp = /(-t8|-t9)(.*)/g; //assuming you only ever have one "-t8"/"-t9" in the URL
  var result = document.URL.match(myRegexp);
  if(result !== null){
    return result[0];
  }else{
    return null; //or whatever you want to return if the ID is not in the URL
  }

}