0

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
2
  • 1
    resourceArr is an Array, not a String. Try resourceArr.find(function (name) { return re.test(name); }).match(re) Commented Feb 13, 2018 at 20:29
  • @PatrickRoberts that worked. Thank you! Commented Feb 13, 2018 at 20:47

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.