How to Split Querystring in JS - javascript

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());

Related

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}`

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);

Escaping JSON to avoid changing the insert string

I have the following json string that should be inserted directly into the database in a single column:
const jsString = JSON.stringify({"escaping":"d\"on't"});
const insertion = [{"a":2,"json":jsString}];
const query = pgp.helpers.insert(insertion,["a","json"],"tbl");
however what actually ends up in the database is:
{"escaping":"d"on't"}
removing the escaping \ in d"on't and making the string invalid json. Is there some way to avoid this?
This would be beneficial since it would be nice if my valid json would remain so.
Don't stringify your data into JSON, use it directly
Set column formatting as JSON, using :json modifier
const data = {escaping: "d\"on't"};
const insertion = [{a:2, json:data}];
const query = pgp.helpers.insert(insertion, ["a", "json:json"], "tbl");
But if your data is always an object, then you don't even need to use the :json modifier, it will be automatically formatted as correct JSON.
For more details see the flexibility of the ColumnSet type. You can manipulate your input data in every thinkable way.
This string in js const jsString = JSON.stringify({"escaping":"d\\\"on't"}); will result in this {"escaping":"d\\\"on't"}
While this string in js const jsString = JSON.stringify({"escaping":"don't"}); will result in this {"escaping":"don't"}

use express.js to get the query string of a url

I'm looking for a way to get the query string part of a url using node.js or one of it's extension module.
I've tried using url and express but they give me an array of parameters.
I want to original string.
Any ideas ?
example; for:
http://www.mydom.com?a=337&b=33
give me
a=337&b=33
(with or without the ?)
Use url.parse. By default it will return an object whose query property is the query string. (You can pass true as the second argument if you want query to be an object instead, but since you want a string the default is what you want.)
var url = require('url');
var urlToParse = 'http://www.mydom.com/?a=337&b=33';
var urlObj = url.parse(urlToParse);
console.log(urlObj.query);
// => a=337&b=33
How about using the built-in url.parse method?

Categories

Resources