Get part of the url and insert it in the button - javascript

There is an address of the type site.com/userlist/?getlist=XXXX&userid=XX. I need to get part of the URL, namely /userlist/?getlist=XXXX&userid=XX and insert the button with the ID reg_button.
I'm leaning towards jquery and apparently regex, but I haven't found a suitable method yet or I don't understand it, I'm just learning)

let url_test=new URL('http://www.yourtestdomain.com/userlist/?getlist=XXXX&userid=XX');
console.log(url_test.pathname+url_test.search);

This takes the url minus base (domain) aswell as the query part, and also URN if exists
documentation
console.log(window.location.href.replace(window.location.origin, ""))

There are many ways to do it. I have included 2 ways here. URL class can also be used as mentioned by one of the answerer but the URL string needs to be complete with http prefix.
If you want it using regex you check this Stackoverflow thread.
var siteurl = "site.com/userlist/?getlist=XXXX&userid=XX";
function method1(){
var paths = siteurl.split('/');
paths.shift();
var basePath = paths.join('/');
alert(basePath);
}
function method2(){
var basePath = siteurl.substring(siteurl.indexOf('/'));
alert(basePath);
}
<button onclick = 'method1()'>Method1</button>
<button onclick = 'method2()'>Method2</button>

Related

How to pass URL query string to website header?

I have this type of URL:
www.domain.com/postname?emailid=somethingsomething
I must place this part:
somethingsomething
inside WP header, more accurate inside JS snippet, as follows:
<script>
window.HashedEmail = 'somethingsomething';
</script>
EDIT: Suggested answer shows how to extract particular data but not how to place extracted data into header, for example - how to manipulate with extracted dataset
Maybe I missed something but this looks like a solution for me
const urlSearchParams = new URLSearchParams(window.location.search);
const emailid = urlSearchParams.get('emailid');
window.HashedEmail = emailid;

Split URL to set cookie using Javascript

Hoping you can help. I think I'm nearly there but my code has a slight error in it. I'm trying to set a cookie which sets the cookie value based on a section of the page url.
For example my cookie name is "model" and my cookie value is populated based on the url
https://www.website.co.uk/cars/100sr/
in the example above the cookie value should be set as 100sr
However, I've just noticed an error, where if the customer visits my website with a query string on the url, it's setting the cookie value to the query string content not the 100sr
e.g.
https://www.website.co.uk/cars/100sr/?testing
the url above using my current code would set the cookie as ?testing when I want it to still be set as 100sr. I'm guessing my code is taking the content after the LAST / is there perhaps a way to specify to take the content after the 2nd / instead?
Code below
<script>$("#carbtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str);
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
If you use the pathname instead of the href, you'll be able to retrieve the portion of the URL without the query string. For example, on the URL:
Split URL to set cookie using Javascript
Using window.location.pathname returns:
"/questions/67402851/split-url-to-set-cookie-using-javascript"
So do:
$("#carbtn").bind("click", function() {
const strings = window.location.pathname.split("/").filter(str => !!str);
document.cookie = `model=${strings[strings.length - 1]};path=/;`
});
<script>$("#carbtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str);
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
This code gets the last element on the split of "/", so "/my/path/" gets the empty string after "path/[HERE]", you might need to dig into the awful (or wonderful) world of regexp for that
const lastItemOnURL = window.location.pathname.match(/[^\/]+\/?$/);
if (lastItemOnURL[0]) { document.cookie = `model=${lastItemOnURL[0].replace('/', '')};path=/;` }
Notice that window.location.pathname doesn't grab the eventual ?get=values in the URL so you probably need that too

Looking for general feedback on a URL-parsing script of mine (Javascript)

I'm fairly new to Javascript, and assembled the following (part is from an example online, rest is by me):
This works reliably, I'm just wondering how many best-practices I'm violating. If someone is nice enough to provide general feedback about the latter part of this script, that would be appreciated.
The two included functions are to (1) capture the incoming website visitor's referral data on a page, including URL query strings for analytics, and store it to a cookie. (2) When the visitor completes a form, the script will read the cookie's URL value, parse this URL into segments, and write the segment data to pre-existing hidden inputs on a form.
Example URL this would capture and parse: http://example.com/page?utm_source=google&utm_medium=abc&utm_campaign=name1&utm_adgroup=name2&utm_kw=example1&kw=example2&mt=a&mkwid=xyz&pcrid=1234
function storeRef() { //this function stores document.referrer to a cookie if the cookie is not already present
var isnew = readCookie('cookiename'); //set var via read-cookie function's output
if (isnew == null) {
var loc=document.referrer;
createCookie('cookiename',loc,0,'example.com'); //create cookie via function with name, value, days, domain
}
}
function printQuery() { //function to parse cookie value into segments
var ref=readCookie('cookiename'); //write cookie value to variable
var refElement = ref.split(/[?&]/); //create array with variable data, separated by & or ?. This is for domain info primarily.
var queryString = {}; //From http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
ref.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
//write segments to form field names below.
document.getElementsByName('example1')[0].value = refElement[0]; //exampleX is a form hidden input's name. I can not use getElementById here.
//need to be able to manually define these, which is why they aren't in a loop, though I'm not sure how to loop an array referenced in this way
document.getElementsByName('example2')[0].value = queryString['utm_source'];
document.getElementsByName('example3')[0].value = queryString['utm_medium'];
document.getElementsByName('example4')[0].value = queryString['utm_term'];
document.getElementsByName('example5')[0].value = queryString['utm_content'];
document.getElementsByName('example6')[0].value = queryString['utm_campaign'];
document.getElementsByName('example7')[0].value = queryString['utm_adgroup'];
document.getElementsByName('example8')[0].value = queryString['utm_kw'];
document.getElementsByName('example9')[0].value = queryString['kw'];
document.getElementsByName('example10')[0].value = queryString['mt'];
document.getElementsByName('example11')[0].value = queryString['mkwid'];
document.getElementsByName('example12')[0].value = queryString['pcrid'];
}
Thank you!
why would you need to use a cookie to store the data for that, if unless you wanna keep track of the visitors visiting to your site?

Django get last GET parameter

I've been working with Django for a few months now so I'm still new at it.
I want to get the last GET parameter from the URL. Here is and example of the URL:
example.com?q=Something&filter1=Test&filter1=New&filter2=Web&filter3=Mine
Is there a way to get the last inserted GET parameter with django? It could be filter1, filter2 or filter3..
Maybe there is a way to do this after the initial refresh with javascript/jQuery?
Thanks!
You can try to parse url parameters yourself. For example:
Python/Django
from urlparse import urlparse, parse_qsl
full_url = ''.join([request.path, '?', request.META['QUERY_STRING']])
#example.com?q=Something&filter1=Test&filter1=New&filter2=Web&filter3=Mine
parameters = parse_qsl(urlparse(full_url)[4])
#[(u'q', u'Something'), (u'filter1', u'Test'), (u'filter1', u'New'), (u'filter2', u'Web'), (u'filter3', u'Mine')]
last_parameter = parameters[-1]
#(u'filter3', u'Mine')
Javascript
var params = window.location.search.split("&");
//["?q=Something", "filter1=Test", "filter1=New", "filter2=Web", "filter3=Mine"]
var last_param = params[params.length-1].replace("?","").split("=");
//["filter3", "Mine"]
This example do not use jQuery and provides basic knowledge of url parsing. There are a lot of libraries, that can do it for you.

Passing an id value into a URL

My company hosts user created surveys on our server. When they are uploaded, they are given a key number as an identifier. I am trying to create a facebook app that people can post a simple survey to and distribute. I can set the canvas URL to the default URL of our server, but I need to pass that key to the query string at the end of the app URL.
<input type="hidden" id="SurveyKey" name="SurveyKey" value="130633791306">
so, the end link needs to be apps.facebook.com/myappname/130633791306
or apps.facebook.com/myappname/SurveyKey value
I am very new to JavaScript and didn't know if there was some get function that could just pull that from the source code and pass it into a new URL. I'm sure this is something easy, but as I am not sure how to word my question, my search result is coming up with a lot of unrelated material.
The URLs for our surveys look like this:
http://www.snapsurveys.com/swh/surveylogin.asp?k=130633791306
where k is a unique value for every survey. I want to be able to pull that value from the source code and pass it into the URL of my facebook app (which has the canvas URL set as our URL). So, it would look like apps.facebook.com/appname/k=VALUE_HERE
To get the query string in JavaScript you could use a code snipet like this:
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
Then you just define a variable to store the key, ie
var surveyKey = querySt("k");
Now you can use the surveyKey anywhere, so for example:
var url = "http://apps.facebook.com/appname/k=" + surveyKey;
http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml

Categories

Resources