How to get URL parameters names only and not values - javascript

There are hundreds of example out here showing how to get URL parameters but I couldn't find any to list ONLY parameters (variables) name and not values?
For example, if I have something like:
www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008
I want to get only makes,models,years and if URL change to
www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler
should be like makes,models
or on
www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008,2010&city=vancouver
the out should be like makes,models,years,city

You can use URLSearchParams
Sample:
const queryString = "?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008"
const urlParams = new URLSearchParams(queryString);
console.log([...new URLSearchParams(urlParams).keys()]);

console.log(
[...new URLSearchParams(window.location.search).keys()].join(',')
);

Related

How to Split Querystring in JS

I am trying to split the value from querystring using window.location.search after that I am getting the below value like
'?path=/dev/dev-alert-banner--alert-banner&args=alertBannerType:dark'
I tried to use like window.location.search.split('/').pop() but i am getting the value like dev-alert-banner--alert-banner&args=alertBannerType:dark
how can i get the value like
dev-alert-banner--alert-banner
using JS
Use the built-in URLSearchParams API to parse the QS for you - then you can do split with pop:
const value = '?path=/dev/dev-alert-banner--alert-banner&args=alertBannerType:dark';
const params = new URLSearchParams(value);
console.log(params.get("path").split("/").pop());

Find elements from concatenate strings in JS

How can I search the values in an Object from strings, something like:
const query = "['arg1']['arg2']"
const renderImage = async (index) => {
const data = await fetchImage(index)
const image = document.querySelector('.div')
image.setAttribute("src", data`${query}`)
}
The fetch function is perfect working.
Edit:
The image source is in the data['arg1']['arg2']. If I use image.setAttribute("src", data['arg1']['arg2']) the code runs fine, but I need to do this dynamically and concatenate strings will help me.
Summing up: can I get the same result data['arg1']['arg2'] concatenating object and "query" (['arg1']['arg2'])?
you can store the path as an array of keys and access it like this
const query = ['arg1', 'arg2']
...
image.setAttribute("src", query.reduce((o, k)=>o[k], data))
It seems you are trying to extract the property names you want, from a poorly formatted string. Ideally, you would get query into a better format to begin with, so you don't have to parse the string. For instance, if you could get query as two separate variables:
const query1 = 'arg1';
const query2 = 'arg2';
image.setAttribute("src", data[query1][query2]);
you could also store query in a better data type to do this, like const query = { arg1: 'arg1', arg2: 'arg2' }; then access with dot syntax data[query.arg1][query.arg2].
But if you must keep query as this weirdly formatted string for some reason, you can do something like this, parsing the string into it's parts, putting them into an array, then using the array to access the right data within data.
let query = "['arg1']['arg2']";
query = query.slice( 2 ).slice( 0, -2 ).split( "']['" );
image.setAttribute( "src", data[query[0]][query[1]] );

passing a dynamic value in between get api url

How to pass a dynamic value in between get api url?
I have a ref that is connected to the input and want value of that input to be passed into a string.
This does not work:
const location = useRef("Warsaw");
"http://api.weatherstack.com/current?&query={location.current.value}"
You have incorrect dynamic string syntax. You should use template literals:
const location = useRef("Warsaw");
let url = `http://api.weatherstack.com/current?&query=${location.current.value}`
You can use template literals
const location = useRef("Warsaw");
const uri = `http://api.weatherstack.com/current?&query=${location.current.value}`

How to remove the url param after it was completed

I am trying to remove the url param after function was completed, so it won't break the uix.
Here how it looks if param is not removed
http://localhost:1337/check?domain=fb.com&success=task&success=note .
I need it to look like this http://localhost:1337/check?domain=fb.com&success=task after every call.
Will be glad for help
Get the URL search query string by window.location.search and parse it with URLSearchParams.
Use getAll(name) to get all values of the parameter as an array.
Remove the desired element from the array.
Edit it back in with set(name, value)
Then use window.location to change the URL with toString()'s result (back as a string).
const searchParams = new URLSearchParams(window.location.search);
const success = searchParams.getAll('success')
success.pop(); // ['task']
searchParams.set('success', success);
window.location.search = searchParams.toString();

http_build_query and URLSearchParams

I have a from with inputs with array name like foo[] so when submitting the form my url become foo[]=lorem&foo[]=ipsum but when using php http_build_query to regenerate this sort of query it adds key to the array like this foo[0]=lorem&foo[1]=ipsum.
My issue is that on the front I'm using URLSearchParams.getAll('foo[]') to get the value, but it works only without the array keys added by http_build_query.
So is there a way to use URLSearchParams with this format ?
Based on #Plamen Nikolov link I fixed my issue by changing my Javascript to handle the inputs that are arrays with or without index keys (added by PHP with http_build_query) like this :
// Before
let urlParams = new URLSearchParams(window.location.search);
// After
let urlQuery = decodeURI(window.location.search).replace(/\[\d+\]/g, "[]");
let urlParams = new URLSearchParams(urlQuery);

Categories

Resources