cphill
cphill

Reputation: 5924

JavaScript - Regex Match Not a Function

I am trying to find a script that was loaded on the page and parse out a query parameter value from its name. My following setup has been tested and pulls out the names of all resources loaded on the page, but I run into the following error when I am trying to pull out the first instance matching my regex string. From this resource name I would like to parse out the value of an individual query string parameter found in the name.

Error:

Capture Snowplow Pixel:25 Uncaught TypeError: resourceArr.match is not a function
    at <anonymous>:25:36

Code:

//Query String Parser
var getQueryString = function ( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};

//Results Array
var resourceArr = [];

//Store Loaded Resources
var resource = window.performance.getEntriesByType("resource");

//Store Names of Loaded Resources
var resourceName = resource.forEach(function(resource){
   return resourceArr.push(resource.name);
 });

console.log(typeof resourceArr);
//RegEx Looking for Snowplow Pixel
 var re = /.*events\.fivetran\.com\/snowplow\/.*\/i\?e=pv.*/i;

//Grab First Snowplow Pixel
var snowplowPixelUrl = resourceArr.match(re);

//Store eid from Snowplow Pixel
var eid = getQueryString(eid, snowplowPixelUrl)

console.log(eid);

Resource Name Example:

https://events.fivetran.com/snowplow/2j32424h2h4/i?e=pv&url=....&eid=j2447

Upvotes: 0

Views: 5015

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51977

As I pointed out in comments, resourceArr is not a string, it's an array, so it does not have the .match() method. First you need to find a string that matches the regex, and then call .match() on it. Array.prototype.find() does just that, but to support older browsers, you need to use this polyfill. Here's how to correct your code:

var snowplowPixelUrl = resourceArr.find(function (name) {
  return re.test(name);
}).match(re);

Upvotes: 0

Tim Han
Tim Han

Reputation: 166

resourceArr you have is an array. match is an instance method on the String class. Maybe that's why you are getting the error saying resourceArr.match is not a function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

Upvotes: 3

Related Questions