Why the url first parameter is not being considered in Javascript? - javascript

const url = new URLSearchParams('https://example.com?q1=1&q2=2');
console.log(url.has('q3')) // returns false as expected
console.log(url.has('q2')) // returns true as expected
console.log(url.has('q1')) // returns false as NOT expected
Why it happens?

The URLSearchParams constructor, if passed a string, expects that string to be a query string and not a complete URL.
q1 doesn't appear because your first parameter is https://example.com?q1.
const url = new URLSearchParams('https://example.com?q1=1&q2=2');
console.log([...url.entries()]);
Use the URL constructor if you want to parse a complete URL.
const url = new URL('https://example.com?q1=1&q2=2');
console.log(url.searchParams.has('q3'))
console.log(url.searchParams.has('q2'))
console.log(url.searchParams.has('q1'))

Related

After running a new URLSearchParams, params.get() returning null

Hello i have an api call to a netlify function which looks like the following:
exports.handler = async(event,context) => {
const params = new URLSearchParams(event.body)
...
}
consoling params returns
'{"items":[{"id":"prod_LvqkrsI9O5F0xJ"}]}', ''
when I try to put the items value in to a variable with
const items = params.get('items')
items returns null
Any ideas please?
You've put the wrong format of data inside the params. Looking at the documentation you need to add the parameters in one of the ways they mention here.
(From the documentation)
One of:
A string, which will be parsed from application/x-www-form-urlencoded format. A leading '?' character is
ignored.
A literal sequence of name-value string pairs, or any object — such as a FormData object — with an iterator that produces a sequence of
string pairs. Note that File entries will be serialized as [object File] rather than as their filename (as they would in an
application/x-www-form-urlencoded form).
A record of string keys and string values. Note that nesting is not supported.
i.e
const params = new URLSearchParams({"id": "prod_LvqkrsI9O5F0xJ"});
Rather than accessing items to get all the params which doesn't work.

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

Parse and extract after '=' in a string in JS [duplicate]

This question already has answers here:
How to get GET (query string) variables in Express.js on Node.js?
(26 answers)
Closed 5 years ago.
Let's say my url atm is
http://test.com/?city=toronto
I'm able to get the requestURL string that is
/?city=toronto
From here, I was wondering if there is a built in function or a standard procedure of extracting the word "toronto" or any other word that comes after the = from the string.
A standard procedure (as you mentioned) of doing this, you can get all the parameter values including value of city or any other parameter you may add to it.
var values = new URL('http://test.com/?city=toronto').searchParams.values();
for(var value of values){
console.log(value);
}
UPDATE
As #taystack mentioned in the comment, if you only want the value of a specific parameter (city) in this case, you can use:
new URL('http://test.com/?city=toronto').searchParams.get('city');
Use split();
var url = '/?city=toronto'.split('=');
console.log(url[1]);
Node.js has a new module called URL, which encodes the semantics of a url string. You don’t need to do any string manipulation.
const URL = require('url')
let my_url = new URL('http://test.com/?city=toronto')
URL#search returns the string representing the search:
my_url.search // '?city=toronto'
URL#query returns the search string excluding ?:
my_url.query // 'city=toronto'
and URL#searchParams returns an object encoding the search string:
my_url.searchParams // something kind of like {'city':'toronto'}
my_url.searchParams.get('city') // 'toronto'
my_url.searchParams.keys() // ['city'] (all the keys)
my_url.searchParams.values() // ['toronto'] (all the values)

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?

Validating URL Query string in Node.js

A correctly formed query string looks like:
http://baseurl.thing/update?id=123&foo=50&bar20
I want to map this "safely" into an object, but I don't want to end up with undefined values. Is there a nice way of validating the query string?
Details: I want to turn this into an object with the url module. i.e.:
var url_parts = url.parse(request.url, true);
and then I can route based on url_parts.pathname. I want to access url_parts.query.id, url_parts.query.foo and url_parts.query.bar, but only if they all exist and only if no other parameters were supplied, so that I don't get silent undefined values appearing.
set up defaults, and then overwrite them with values from your url.
EXAMPLE
var defaults = {
id : 0,
foo : 'default value',
bar : 'default.value'
};
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
query.prototype = defaults; //does the inheritance of defaults thing
// now query has all values set, even if they didn't get passed in.
Hope that helps!

Categories

Resources