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
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
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);
Related
I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get query string values in JavaScript
I am working on a extension for Chrome.
I already figured out how to get the URL from the actual Chrome-Tab.
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
But now i need to know how to get a specific Parameter from the URL.
I already tried out different Javascript-Functions but when i implement them, my Extension stops working.
So:
How can i get a specific parameter from the actual URL?
To get a query string in a single regexp, use:
var queryString = /^[^#?]*(\?[^#]+|)/.exec(tab.url)[1];
// Explanation of RegEx:
// ^[^#?]* (\?[^#]+ | )
// <Starts with any non-#/? string><query string OR nothing>
Then, use the following function to get the value of a specific key:
function getParameterByName(queryString, name) {
// Escape special RegExp characters
name = name.replace(/[[^$.|?*+(){}\\]/g, '\\$&');
// Create Regular expression
var regex = new RegExp("(?:[?&]|^)" + name + "=([^&#]*)");
// Attempt to get a match
var results = regex.exec(queryString);
return decodeURIComponent(results[1].replace(/\+/g, " ")) || '';
}
// Usage:
// Example: tab.url = "http://example.com/path?foo=bar&key_name=qs_value#"
var queryString = /\?[^#]+(?=#|$)|$/.exec(tab.url)[0];
var value = getParameterByName(queryString, 'qs_name');
// Result : value = "value";
// Example 2: Using the function to get a parameter from the current page's URL.
// (e.g inside content script)
var value = getParameterByName(location.search, 'qs_name');
// Result : value = "value"
Not exactly a regex, but this should work:
var queryString=url.match(/\?.+$)[0].split('#')[0]
This should work in most cases. I'll try to dig up the regex I had written for this some time ago.
Created simple function to get URL parameter in Javascript from a URL like this
.....58e/web/viewer.html?page=17&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT : 18
Let's say I have the following url:
something.com/messages/username/id
How can I get the username or id?
You can use String.split for that:
var parts = window.location.href.split('/'); # => ["http:", "", "something.com", "messages", "username", "id"]
var username = parts[4];
var id = parseInt(parts[5]);
I guess you could use the window.location.href to get the URL and then string.split() the URL on /.
var urlParts = window.location.href.split("/");
var username = urlParts[4];
var id = urlParts[5];
I actually just had to deal with the other day. When you're accessing the cached version of some of our pages, the query string is actually part of the URL path. But if you're trying to avoid the cache, you use a query string.
Given one of the answers from How to get the value from the GET parameters? here's what I'm using to partially normalize access.
The router that takes the response does _.isArray() (we're built on top of backbone, so we have underscore available) and handles pulling the data out of the object or array in a different manner.
The slice at the end gets rid of the two "" since we're not using documents, just directories and our URLs start and end with /. If you're looking for document access, you should alter the slice accordingly.
var qs = function(){
if(window.location.search){
var query_string = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
})();
} else {
return window.location.pathname.split('/').slice(1, -1);
}
return query_string;
};
You could split your url on every '/' character like this:
var url = "something.com/messages/username/id";
var array = url.split('/');
// array[2] contains username and array[3] contains id
Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions
i took a ready script from here, How to read GET data from a URL using JavaScript? and can't make it work, what im doing wrong?
here is my script:
function getUrlParam(param)
{
param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
var regex = new RegExp("[?&]" + param + "=([^&#]*)");
var url = decodeURIComponent(window.location.href);
var match = regex.exec(url);
return match ? match[1] : "";
}
var param = getUrlParam("process_number");
alert(param);
and here is my link:
http://erp.micae.com/index.cfm?fuseaction=objects.popup_print_files&process_number=SER-498&action_type=141&action_id=289&action_row_id=32&print_type=192
thx for the help!
Sorry guys, forgot to mantion that my page is working in a frame, that why it can't get the data from url i want :)
Since you're in a frame, if you need to get the href from the main window, do this:
var href = window.top.location.href;
Then process it.
That code has to run from the page whose URL you're mining for parameter values. In other words, it operates only on the current URL of the page it's on. It works fine.
If you want a function that gives you parameter values given an arbitrary URL, you'd just need to add an additional parameter:
function getUrlParam(param, url) {
param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
var regex = new RegExp("[?&]" + param + "=([^&#]*)");
url = url || decodeURIComponent(window.location.href);
var match = regex.exec(url);
return match ? match[1] : "";
}
alert(getUrlParam("process_number", "http://erp.micae.com/index.cfm?fuseaction=objects.popup_print_files&process_number=SER-498&action_type=141&action_id=289&action_row_id=32&print_type=192"));