Filip Kapusta
Filip Kapusta

Reputation: 165

How do I fix this RegExp problem with JavaScript Compiler Error in GTM?

When trying to publish new GTM version I get errors with variables that I haven't edited (they used to work, and now they're showing errors).

Error message:JavaScript Compiler Error Error at line 4, character 18: Cannot convert ECMASCRIPT_2018 feature "RegExp Lookbehind" to targeted output language.

Code:

function(){

  var myRegexp = /(?<=(\/.*\/cat\/)).*?(?=\/)/g; //regex rule
  var result = document.URL.match(myRegexp);
  if(result !== null){
    return result[0];
  }else{
    return null;
  }

}

Upvotes: 2

Views: 1147

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370819

Lookbehind is a pretty new feature - only some browsers support it, and it can't exactly be transpiled (as far as I've seen), thus the error. Use standard matching instead of lookbehind, with a capturing group for the part after cat/, and return the first capturing group:

var pattern = /\/.*\/cat\/([^/]+)/;
var match = document.URL.match(pattern);
return match
? match[1]
: null;

Upvotes: 1

Related Questions