Simple code to extract substring into a variable of GTM (Google Tag Manager)

Viewed 564

I do not know how to code Java and am not an expert in GTM. However, the code I need is so simple, It worked on an online editor but I have been trying to get it to work on GTM and it does not validate the code.

I need to extract the email adresses from a long string (variable {{Click URL}} in GTM) that contains a complete "mailto:" url with many parameteres and only extract the short email from there (without the additional parameters after the ".com?")

Just an example of this kind of url: 'mailto:information@example.com?subject=Demande%20de%20renseign ements&body=Votre%20nom:%20%0A%0ANom%20du%20produit:%20%0A%0AVotre%20tel .%20si%20vous%20souhaitez%20recevoir%20un%20appel%20de%20notre%20part:%2 0%0A%0AVotre%20demande%20de%20renseignements:%20%0A'

Here is the code,


let shortmailto2 = {{Click URL}},
let fin = shortmailto2.indexOf('?'),
let debut = shortmailto2.indexOf(':'),
let shortmailto = shortmailto2.slice(debut+1,fin);

it pulls the right email address as I need when testing on an online editor but when I insert it into GTP (and use a pre-existinge variable, the "click url") I get an error (see monosnap link below for the screen shot): https://monosnap.com/file/eBFYfEwLv9LrPwGrGl6rzaHCbmoeYj

Thanks!

1 Answers

GTM Custom JavaScript Variables:
This field should be a JavaScript function that returns a value using the 'return' statement. If the function does not explicitly return a value, it will return undefined and your container may not behave as expected. Below is an example of this field:

  function() {
    var now = new Date();
    return now.getTime();
  }  

The following worked for me when I tested it, returning just the email address.

 function() {
  var shortmailto2 = {{Click URL}};
  var fin = shortmailto2.indexOf('?');
  var debut = shortmailto2.indexOf(':');
  return shortmailto2.slice(debut+1,fin);      
}
Related