JavaScript get value of query string parameter - javascript

I can't find any splitter solution JS to obtain one parameter in this URL
https://www.test.be/fr_BE/home/forms/test-test-salon.html?configId=f4q8s9z1&ucpBaseurl=https%253A%252F%252Ftest.client.ucp.cloud&model=F56&motorization=Diesel
The part I want to isolete is the model id, model=F56, in this case I want to isolate "F56"
I tried this script without success:
var srcID = "11111"; // Insert your src ID here
var typeID = "11111"; // Insert your type ID here
var category = "m1111"; // Insert your category value here
var axel = Math.random() + ""; var a = axel * 10000000000000;
// Grab Data Layer
var dataLayerApi = digital.tracking.getInstance(dataLayer);
var digitalData = dataLayerApi.getPageObject((window.minidtm.actPageId !== undefined) ? window.minidtm.actPageId : dataLayerApi.getCurrentPageIndex());
var path = document.location.pathname;
var pathHirarchy = path.split("&");
if(path.match("\/fr_BE\/home\/forms\/.*\/.*") != null) {
// Get Model Info
var u1 = pathHirarchy[1] //U1 - Produit
var u2 = pathHirarchy[5].split(".")[0] //U2 - Sous Produit
}
else {
var u1 = "notApplicable";
var u2 = "notApplicable";
}
var DCtag = document.createElement("iframe");
DCtag.src = "https://" + srcID + ".fls.test.net/activityi;src=" + srcID + ";type=" + typeID + ";cat=" + category +
";u1=" + u1 +";u2=" + u2 + ";dc_lat=;dc_rdid=; tag_for_child_directed_treatment=;ord=1;num=" + a;
DCtag.width = "1"; DCtag.heigth = "1"; DCtag.frameborder = "0"; DCtag.style = "display:none"; DCtag.async = true;
document.body.appendChild(DCtag);
Do you have an idea ? Expertize in ?
Big big Thanks !
Ludo

You could use URLSearchParams
const params = new URLSearchParams(window.location.search);
const model = params.get('model');
If model isn't present in the query string params.get('model') will return null.
For more information on URLSearchParams.get see the MDN documentation

You could use a regexp:
const url = 'https://www.test.be/fr_BE/home/forms/test-test-salon.html?configId=f4q8s9z1&ucpBaseurl=https%253A%252F%252Ftest.client.ucp.cloud&model=F56&motorization=Diesel';
const result = url.match(/model=(.*?)&/);
const model = result[1];
console.log(model);
EDIT:
I'm gonna leave this answer here, but bflemi3's answer is better.

Related

searchParams.get returning "Null" when values are present

I'm trying to grab URL params from a page link to prepopulate a form in an iFrame, but am struggling with the params returning 'null' and need some guidance. So far, the script appears to work by populating the form with "null", however, it is unsuccessfully populating params that have valid values in my URL. The javascript below 'f.src' is scripting provided by my forms service.
(I apologize for the ugly console.logs, but am using those for troubleshooting.)
[Console Preview][1]
***UPDATE: With my updated code, per user suggestion, I updated my .get statements to specify the param with a string, but it's still returning 'null'.
try{
var endpoint = "https://forms.myformsite.com/";
console.log(endpoint);
var url_string = "https://my.site.com/landingpage?fname=Jeff&lname=Bezos&email=jeff#amazon.com&company=Amazon&title=Founder"; /*window.location.href;*/
console.log(url_string);
var url = new URL(url_string);
console.log(url_string);
var fname = url.searchParams.get('fname');
console.log(fname);
var lname = url.searchParams.get('lname');
console.log(lname);
var email = url.searchParams.get('email');
console.log(email);
var company = url.searchParams.get('company');
console.log(company);
var title = url.searchParams.get('title');
console.log(title);
var formURL = endpoint+"&fname="+fname+"&lname="+lname+"&email="+email+"&company"+company+"&title="+title;
console.log(formURL);
var f = document.createElement("iframe");
f.src = formURL;
console.log(f.src);
f.style.border = "none";
f.style.height = "878px";
f.style.width = "90%";
f.style.transition = "all 0.5s ease";
var d = document.getElementById("divFormID");
d.appendChild(f);
window.addEventListener('message', function() {
var evntData = event.data;
if (evntData && evntData.constructor == String) {
var zf_ifrm_data = evntData.split("|");
if (zf_ifrm_data.length == 2) {
var zf_perma = zf_ifrm_data[0];
var zf_ifrm_ht_nw = (parseInt(zf_ifrm_data[2], 10) + 15) + "px";
var iframe = document.getElementById("divFormID").getElementsByTagName("iframe")[0];
if ((iframe.src).indexOf('formperma') > 0 && (iframe.src).indexOf(zf_perma) > 0) {
var prevIframeHeight = iframe.style.height;
if (prevIframeHeight != zf_ifrm_ht_nw) {
iframe.style.height = zf_ifrm_ht_nw;
}
}
}
}
}, false);
} catch (e) {}
})();```
[1]: https://i.stack.imgur.com/z75q0.png
[2]: https://i.stack.imgur.com/bjqoP.png
For all .get() calls, you're passing in an (undefined) variable instead of a string:
var fname = url.searchParams.get(fname);
This should be:
var fname = url.searchParams.get('fname');

How add a filter in server script with query

i'm new in servicenow and I have to add this filter "document_id.number STARTS WITH BKNG"
as a query, how can i do in servicenow?
this is my code:
// only show 30 in header menu dropdown
var max = 30;
var t = data;
t.items = [];
t.count = 0;
var u = getMyApprovals();
// use record watchers to tell header when to update dropdown counts
t.record_watchers = [];
t.record_watchers.push({'table':'sysapproval_approver','filter':'approverIN' + u.toString() + '^state=requested'});
var z = new GlideRecord('sysapproval_approver');
z.addQuery("approver", u);
z.addQuery("state", "requested");
z.addQuery("document_id.number", "STARTSWITH", "BKNG")
z.orderByDesc('sys_updated_on');
z.setLimit(max);
z.query();
var link = {};
link.title = gs.getMessage('View all approvals');
link.type = 'link';
link.href = '?id=approvals';
link.items = [];
t.items.push(link);
while (z.next()) {
var a = {};
var rec = getRecordBeingApproved(z);
if (!rec.isValidRecord()) // nothing being approved - hmmm
continue;
a.short_description = rec.short_description + "";
if (rec.getRecordClassName() == "sc_request") {
var items = new GlideRecord("sc_req_item");
items.addQuery("request", rec.getUniqueValue());
items.query();
if (items.getRowCount() > 1)
a.short_description = items.getRowCount() + " requested items";
else if (items.getRowCount() == 1) {
items.next();
a.short_description = items.getValue("short_description");
}
}
$sp.getRecordValues(a, z, 'sys_id,sys_updated_on');
a.number = rec.getDisplayValue();
a.__table = z.getRecordClassName();
a.type = 'approval';
t.items.push(a);
t.count++;
}
function getRecordBeingApproved(gr) {
if (!gr.sysapproval.nil())
return gr.sysapproval.getRefRecord();
return gr.document_id.getRefRecord();
}
i tried doing z.addQuery ("document_id.number", "STARTSWITH", "BKNG")
but it doesn't works.
i don't know how to do.
You can't dot-walk the document_id field when using .addQuery() as it is not a reference filed. Instead, you can use the Approval for (sysapproval) reference field like so:
z.addQuery("sysapproval.number", "STARTSWITH", "BKNG");

How to pass a JavaScript variable to XML?

I want to pass JavaScript variable's value to an XML file. I have already seen this question and answer here but since my XML file is not that small but rather big, I would like to know how to do this without writing whole xml if possible.
I have this JavaScript code
render_receipt: function () {
// this._super();
var self = this;
if (self.pos.config.disable_fiscalization == false) {
var data = self.get_receipt_render_env();
self.$('.pos-receipt-container').html("")
var total_amount = data['receipt']['total_with_tax'];
var vat = self.pos['company']['vat'];
var header_time = data['order']['formatted_validation_date'];
var order_name = data['order']['name'];
var soft_code = self.pos['company']['software_code'];
var business_unit_code = self.pos['config']['business_unit_code'];
var business_unit_address = self.pos.business_unit_address
var tcr_code = self.pos['config']['tcr_code'];
var operator_code = self.pos.get_cashier().operator_code
// create message
message = vat + '|' + header_time + '|' + order_name + '|' + business_unit_code + '|' + tcr_code + '|' + soft_code + '|' + total_amount
var order = self.pos.get_order();
if (!this.pos.config.iface_print_via_proxy) {
var invoiced = new $.Deferred();
// if (self.pos.config.disable_fiscalization == false) {
// console.log("hasEnoughSpeed", hasEnoughSpeed, isAlive)
if (isAlive && hasEnoughSpeed) {
rpc.query({
model: 'pos.order',
method: 'search_read',
domain: [['pos_reference', '=', order['name']]],
fields: ['iic_code', 'header_send_datetime', 'amount_total', 'fic', 'business_unit_code', 'operator_code', 'fiscalization_url', 'partner_id']
})
.then(function (orders) {
var partner = null;
if (orders.length && orders[0]['partner_id'] == false) {
var data = self.get_receipt_render_env();
data['partner_name'] = orders[0]['partner_id'][1];
data['street'] = false;
data['country'] = false;
data['city'] = false;
data['zip'] = false;
data['vat'] = false;
data['nslf'] = orders[0]['iic_code'];
// alert(data['nslf'])
data['nivf'] = orders[0]['fic'];
data['business_unit_code'] = business_unit_code;
data['operator_code'] = operator_code;
data['business_unit_address'] = business_unit_address
self.$('.pos-receipt-container').html(qweb.render('PosTicket', data));
var qr = new QRious({
element: document.getElementById('qr-code'),
size: 200,
});
I'd like to pass data['nsfl'] to this XML div tag. I have already tried as you see and it is failing, I get why it is failing and from the other side I don't know how to make work either. Thanks in advance guys!!!
<div>
<div style="font-weight:bold;font-size:12px;">NSLF: <t t-esc="data['nslf']"/></div>
</div>

Regular Expression: how to replace a string (as a variable) that has a digit in it?

var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var value = 10;
How do I replace the &filters[]=price_gte:20 part with the new path? (path + value)
I've tried RegExp():
var re = new RegExp(path);
console.log(url.replace(re, ''));
//returns http://mywebsite.com/?&filters[]=price_gte:20
That didn't even work, let alone adding the digit in the regex. Problem is, price_gte is a variable (and so will price_lte be, and whatever other ranges there might come), with a variable digit after it.
Information I have:
url (http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100)
path (&filters[]=price_gte:)
new value (10)
Desired result:
http://mywebsite.com?&filters[]=price_gte:10&filters[]=price_lte:100
What am I missing?
You were almost there, just needed to escape the brackets:
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var regexPath = '&filters\\[\\]=price_gte:\\d+';
var value = 10;
var re = new RegExp(regexPath);
console.log(url.replace(re, path+value));
Perhaps you meant this
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = 'filters[]=price_gte:';
var value = 10;
var re = /filters\[\]=price_[g|l]te:\d+/;
alert(url.replace(re,path+value))
However a better solution might be
// from http://stackoverflow.com/a/20420424/295783
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1' + paramValue + '$2');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var value=10;
url = replaceUrlParam(url,"filters[]", 'price_gte:'+value);
alert(url)
This seems to work for me:
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/&filters\[\]=price_gte:\d+/, "&filters[]=price_gte:" + value);
alert(newStr);
}
This is enough for getting new value
var str = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100';
var pattern = /price_gte:\d+/;
var new_value = 10;
str = str.replace(patter, 'price_gte:'+new_value);
And Simple Solution will be =>
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/(\w*)(price_gte:)(\d*)/i,"price_gte:"+ value);
alert(newStr);
}

Updating existing URL querystring values with jQuery

Let's say I have a url such as:
http://www.example.com/hello.png?w=100&h=100&bg=white
What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:
http://www.example.com/hello.png?w=200&h=200&bg=white
So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?
So:
Get the values of each querystring key
Update any number of the keys
Rebuild the url with the new values
Keep all of the other values which weren't updated
It will not have a standard set of known keys, it could change per URL
Simple solution
You can use URLSearchParams.set() like below:
var currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var url = new URL(currentUrl);
url.searchParams.set("w", "200"); // setting your param
var newUrl = url.href;
console.log(newUrl);
Online demo (jsfiddle)
Get query string values this way and use $.param to rebuild query string
UPDATE:
This is an example, also check fiddle:
function getQueryVariable(url, variable) {
var query = url.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var w = getQueryVariable(url, 'w');
var h = getQueryVariable(url, 'h');
var bg = getQueryVariable(url, 'bg');
// http://www.example.com/hello.png?w=200&h=200&bg=white
var params = { 'w':200, 'h':200, 'bg':bg };
var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);
You can change the function to use current url:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
//update URL Parameter
function updateURL(key,val){
var url = window.location.href;
var reExp = new RegExp("[\?|\&]"+key + "=[0-9a-zA-Z\_\+\-\|\.\,\;]*");
if(reExp.test(url)) {
// update
var reExp = new RegExp("[\?&]" + key + "=([^&#]*)");
var delimiter = reExp.exec(url)[0].charAt(0);
url = url.replace(reExp, delimiter + key + "=" + val);
} else {
// add
var newParam = key + "=" + val;
if(!url.indexOf('?')){url += '?';}
if(url.indexOf('#') > -1){
var urlparts = url.split('#');
url = urlparts[0] + "&" + newParam + (urlparts[1] ? "#" +urlparts[1] : '');
} else {
url += "&" + newParam;
}
}
window.history.pushState(null, document.title, url);
}
I like Ali's answer the best. I cleaned up the code into a function and thought I would share it to make someone else's life easier. Hope this helps someone.
function addParam(currentUrl,key,val) {
var url = new URL(currentUrl);
url.searchParams.set(key, val);
return url.href;
}
Another way (independent of jQuery or other libraries): https://github.com/Mikhus/jsurl
var u = new Url;
// or
var u = new Url('/some/path?foo=baz');
alert(u);
u.query.foo = 'bar';
alert(u);
My URL is like this: http://localhost/dentistryindia/admin/hospital/add_procedure?hid=241&hpr_id=12
var reExp = /hpr_id=\\d+/;
var url = window.location.href;
url = url.toString();
var hrpid = $("#category :selected").val(); //new value to replace hpr_id
var reExp = new RegExp("[\\?&]" + 'hpr_id' + "=([^&#]*)"),
delimeter = reExp.exec(url)[0].charAt(0),
newUrl = url.replace(reExp, delimeter + 'hpr_id' + "=" + hrpid);
window.location.href = newUrl;
This is how it worked for me.
Another way you you can do this, using some simple reg ex code by Samuel Santos here like this:
/*
* queryParameters -> handles the query string parameters
* queryString -> the query string without the fist '?' character
* re -> the regular expression
* m -> holds the string matching the regular expression
*/
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
// Creates a map with the query string parameters
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// Update w and h
queryParameters['w'] = 200;
queryParameters['h'] = 200;
Now you can either create a new URL:
var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
// Build new Query String
var params = $.param(queryParameters);
if (params != '') {
url = url + '?' + params;
}
OR you could just use the params to cause browser to reload right away:
location.search = params;
OR do whatever you want with :)
You could do something like this:
// If key exists updates the value
if (location.href.indexOf('key=') > -1) {
location.href = location.href.replace('key=current_val', 'key=new_val');
// If not, append
} else {
location.href = location.href + '&key=new_val';
}
Regards
URI.js seems like the best approach to me
http://medialize.github.io/URI.js/
let uri = URI("http://test.com/foo.html").addQuery("a", "b");
// http://test.com/foo.html?a=b
uri.addQuery("c", 22);
// http://test.com/foo.html?a=b&c=22
uri.hash("h1");
// http://test.com/foo.html?a=b&c=22#h1
uri.hash("h2");
// http://test.com/foo.html?a=b&c=22#h2
Alright, If you are someone like me who only wants to update query string on URL without reloading the page. try following code
updateQueryString('id',post.id)
function updateQueryString(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
$('.desktopsortpriceHandler').on('change', function(){
let price_id = $(this).val()
$('.btn_product_locality_filter').attr("href", function (i, val) {
// if p is in between of url
val = val.replace(/p=.*?&/i, ""); ----> this will help to get the parameter using regex and replace it with ""
// if p at the end of url
val = val.replace(/&p=.*?$/i, ""); ----> this will help to get the parameter using regex and replace it with ""
return val + `&p=${encodeURIComponent(price_id.toString())}`; ---> then you can add it back as parameter with new value
});
})
i'm using this
function UpdateUrl(a,b,c,pagetitle) {
var url = window.location.href;
var usplit = url.split("?");
var uObj = { Title: pagetitle, Url: usplit[0] + "?w=a&h=b&bg=c};
history.pushState(uObj, uObj.Title, uObj.Url);
}

Categories