JavaScript: How to get first parameter, actually first key from URL? - javascript

I am trying to get first key from URL, like this:
const currentUrl = window.location.href;
const parmsFromUrl = new URLSearchParams(currentUrl);
const paramToCheck = parmsFromUrl.keys[0];
But constantly I get undefined, can someone tell how me how to get only first parameter, not a value, I just want key? Thanks.

With URLSearchParams you have to use window.location.search
With URL you have to use window.location.href
const currentUrl = window.location.search;
const parmsFromUrl = new URLSearchParams(currentUrl);
URLSearchParams.keys() returns an iterator, so you have to use next() to get first value
const paramToCheck = parmsFromUrl.keys().next().value;

Related

How to insert dynamic URL parameters in HTML (Javascript)

I'm working on a marketing landing page that would take parameters in a URL and then display them in the HTML of an id on the page. Right now, I have every text placeholder defined in addition to each parameter from the URL.
The code below is working fine, but is there a way to remove the redundancies so that if any id matches the name of a parameter in the URL (e.g. a span has id "city" is automatically matched with the parameter "city"), they recognize and update the inner HTML? Thanks for any help.
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const company_text = document.getElementById("company");
const company = urlParams.get('company');
if (company != null){
company_text.innerHTML = company;
}
const city_text = document.getElementById("city");
const city = urlParams.get('city');
if (city != null){
city_text.innerHTML = city;
}
Edited to update parameter names for clarity
You could put something like this at the end of your page
for(const [id, val] of urlParams.entries()) {
const htmlElement = document.getElementById(id);
if(htmlElement) {
htmlElement.innerHTML = val;
}
}
Keep in mind that the same parameter can appear more than one time in the query string (e.g. ?x=1&x=2). In that case there will be two entries with the same id.
Ref for entries.
This can be done by iterating over a list of all URL parameters and changing the HTML content of elements with the correct IDs.
var parameters = new URLSearchParams(window.location.search);
for (const parameter of parameters) {
document.querySelectorAll(`[id=${parameter[0]}]`).forEach(element => {
element.innerHTML = parameter[1];
});
}
I hope this solves your problem.
Best Regards,

Best way to get the pathname from string

I am trying to get the first segment of the path from a string.
Current Behaviour:
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split('/')[1];
console.log(resultOne, resultTwo, resultThree);
As you see in the above code, I tried split the string and get second element from the array which has the first segment of the path.
But unfortunately in the last one, I get query params along with it, which I intend to remove it and get only tasks for all three strings.
Kindly please help me with efficient way of achieving the result that gives only the first segment of the path and ignore query params.
Note:
Please don't consider it as url and it is just a normal string with pathname and I am intend to get only the first segment of it tasks .
You can do somethong like this
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const getFile = fullPath => {
const [path, query] = fullPath.split('?')
return path.split('/')[1]
}
console.log(getFile(pathOne));
console.log(getFile(pathTwo));
console.log(getFile(pathThree));
You have index key after .split() -> [1]. When you have key index, you told "Give me first separated word from string"
If you remove it, you can get every string separated by "/". Try :)
const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/');
const resultTwo = pathTwo.split('/');
const resultThree = pathThree.split('/');
console.log(resultOne, resultTwo, resultThree);
EDIT: IF you don't wanna query parameters, you must split "pathThree" string also by "?"
If you're getting the string from the window object you can obtain the pathname from the window.location property
const pathParts = window.location.pathname.split('/');
Otherwise you can construct an URL object
const myUrl = new URL('https://www.example.com/get/the/pathname?param=1&param=2');
const pathParts = myUrl.pathname.split('/');
If you're working on a path string (not a valid url) I'd suggest something like
const myStr = '/get/the/pathname?paramA=1&paramB=2';
const parts = myStr.split('?')[0].split('/');
enter code hereconst pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';
const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split(/[/?_]+/)[1];
console.log(resultOne, resultTwo, resultThree);

Get url parameter with javascript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 months ago.
I try to get a URL parameter nr, but I get always false.
var url = window.location.href;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
What is the error?
Use
var url = window.location;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
because window.location is a Location object with a .search property
whereas window.location.href is a string, without a .search property
therefore your url.search is undefined
I can demonstrate with URL which is similar to Location in this respect
let loc = new URL('http://example.com/?nr=1');
// loc is a placeholder for your window.location
let url = loc.href;
// here, url.search would be window.location.href.search
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
console.log(nr);
url = loc;
// here, url.search would be window.location.search
params = new URLSearchParams(url.search);
nr = params.has('nr')
console.log(nr);
The below function will return Array of all parameters from url
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var params = getUrlVars();
console.log(params["nr"]);
reference taken from https://stackoverflow.com/a/20097994/8077687
From https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present.
So you should only provide the query params string.
e.g. if your window.location.href is
https://stackoverflow.com/questions/68314446/get-url-parameter-with-javascript?query=1&query_1=2&many_queries=3
Then you should pass the URLSearchParams class only the query params, viz
query=1&query_1=2&many_queries=3

print value of URL Parameters hash js

I am trying to get the parameters from a URL using js i have a url :
http://www.example.com?i=aGVsbG8gd29ybGQ=
i want to decode base64 ?i value and print decode value here using javascript
<input id="i" type="hidden" value="decode value" />
Try this :
var parameterValue = atob(window.location.search.match(/(\?|&)i\=([^&]*)/)[2])
console.log(parameterValue);//"hello world"
document.getElementById('i').value=parameterValue;
This might help too : https://stackoverflow.com/a/26995016/957026
you could use the window.location API https://developer.mozilla.org/en-US/docs/Web/API/Location
console.log(window.location.search);
You will get as a response ?i=some-value
Yes you can get the value from url and and decode it.
Use below code
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
let x = atob(getUrlVars().i);
console.log(x); // hello world
document.getElementById('i').value = x;
To parse URL strings, modern browsers provide a class called URLSearchParams and this is the easiest way to extract URL values.
You can create an instance of that class by passing it the search property of window.location (after removing the initial "?"), and then it will do all the work for you:
// eg. https://example.com/?name=Jonathan&age=18&i=aGVsbG8gd29ybGQ=
const params = new URLSearchParams(window.location.search.substring(1)); // remove "?"
const name = params.get("name"); // is the string "Jonathan"
const age = parseFloat(params.get("age")); // is the number 18
const i = whateverDecodingFunctionYouUse(params.get("i")); // decoded aGVsbG8gd29ybGQ
See: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/

Javascript input id value to url

I would appreciate any help to build a basic javascript that would extract the forum input name value and create a new URL from the value that is extracted, and repeat with the new URL until the value that extracted is -1. That would be the final URL. Once found the final url will be opened.
For example if the source code states that
<input name="nextPage" ... value="10908071">
The script would extract the nextPage value which is 10908071 and input it into the url thus forwarding to www.url.com/xyz?page=10908071
When the next url is identified the script will loop and extract the nextPage value once again until the value is -1.
Once the value is -1 the final web url will be found and preferably opened.
Any help is greatly appreciated.
p.s. this is my first post, I would always find my answer here without the need to post but this seems a bit more complicated.
Just use a loop and make network requests until you get to the desired value:
async function findURL() {
let value;
const baseURL = window.location.href; // I assume this is eg 'www.url.com/xyz'
let pageURL = baseURL;
while (value !== '-1') {
const response = await fetch(pageURL);
const responseText = await response.text();
const responseDocument = (new DOMParser()).parseFromString(responseText, 'text/html');
value = responseDocument.querySelector('input[name="nextPage"]').value;
if (value !== '-1') pageURL = baseURL + '?page=' + value;
}
// final URL found, redirect to its page:
window.location.href = pageURL;
}
But you'll have to be pretty certain that the value eventually ends up being -1.

Categories

Resources