How can I insert dynamic value to URL in cy.visit()? - javascript

I am trying to insert value to URL which I want to visit. I use this (for example):
const idp = '10'
cy.visit('http://test.com/aaa/bbb?id=${idp}')
but when I run this, it will ends on this http://test.com/aaa/bbb?id=$%7Bidp%7D
instead of id=10.
Also I am interested how can I get value from URL to variable.
For example I have URL http://test.com/aaa/bbb?id=5 and I want to create variable idc which will have value 5.

I think you are using the wrong quotes, you need to use backticks to use Template Literals:
cy.visit(`http://test.com/aaa/bbb?id=${idp}`)
You can then use cy.url() to get the current URL as a string and use JavaScript to parse the string as normal.

For the first part of your question you need to use backticks(also called grave accents) as outlined in the Template Literals docs instead of regular quotes. Your line would then look like -
cy.visit(`http://test.com/aaa/bbb?id=${idp}`)
For the second part of your question, you can use URLSearchParams (Note this DOES NOT work in IE). An example would be -
var url = new URL("http://test.com/aaa/bbb?id=5");
var searchParams = new URLSearchParams(url.search);
const urlParams = new URLSearchParams(searchParams );
const myParam = urlParams .get('id');

Related

How to decode a url in JavaScript or NextJS?

In our NextJS application we have a URL that is fed with various query strings.
With some query strings, however, we have the problem that they are displayed in encoded form. For example like this:
http://localhost:8080/my-app/test-app?project=project%3Aone&project=project%3Atwo
As you can see, the colons are replaced with %CA.
I know that this may be a default behavior, but I need the colons in the URL.
Is there any way I can get this? So I need to URL above like:
http://localhost:8080/my-app/test-app?project=project:one&project=project:two
We are using URLSearchParams() like this:
const constructQueryString = (params: any) => {
const searchParams = new URLSearchParams();
const projects = params.project.split(',');
projects.forEach((p) => {
urlSearchParams.append('project', p);
});
return searchParams.toString();
};
These are escape codes for special characters in the URL that are necessary and cant be avoided. Also, there's no need for you to use URLSearchParams. Just use router.query will give you query and router.pathname for the path (/my-app/test-app) in nextJS
Use the decodeURIComponent global function in Javascript
const decodedPath = decodeURIComponent("http://localhost:8080/my-app/test-app?project=project%3Aone&project=project%3Atwo")
The Result is what you want as below:
http://localhost:8080/my-app/test-app?project=project:one&project=project:two

How to ignore invalid URL parameters?

Before I go on, let me say that I've looked through a number of threads already and can't find an answer that works for me.
Basically, I've built a custom link shortener and I'm using URLSearchParams to pull the URL to be shortened and the custom slug from the URL search query as follows:
var e = window.location.search;
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
Where the format for a query is: ?url=https://google.com&slug=customslug
After the parameters are handled, the URL string is treated with trim() to remove any whitespace. The final output is encoded with encodeURIComponent() when the API I'm using (https://short.io) is called.
However, I want to be able to pass URLs with &, like so: ?url=https://google.com/&testing&slug=customslug. My ideal solution would simply treat any & that isn't part of the &slug parameter as a part of the URL contained within the &url parameter. Currently, the & character is ignored if it isn't attached to a valid parameter (url or slug).
I have tried encoding the query input using encodeURIComponent(), but that results in a failure to pick up on either defined parameter. I have also tried splitting the input using split("&slug",1), but that results in an array and I cannot pass arrays to the Short.io API.
Any suggestions?
You should use the URL Encoded ampersand symbol %26.
var e = "?url=https://google.com/%26testing&slug=customslug";
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
console.log(url);
console.log(slug);
I solved my issue by building off of #CherryDT's comment about using window.location.hash to get my URL string. Ultimately, I chose to forgo the idea of a slug in the address bar, since it would cause further problems with my script.
While this solution is only applicable for my purposes, I'm detailing the solution because it functions as a workaround for the issue of not being able to encode a passed URL string from the address bar. Might be useful to someone, someday.
var e = window.location.href.replace(window.location.hash, '');
if (e.endsWith("?") === true) {
var url = window.location.hash.substr(1);
if (url === "") {
// Error code
} else {
console.log("A URL to be shortened was provided via hash.");
// Pass url to rest of script
}
}

Get values of parameters from URL

I’m working on a tool which takes the value parameters in the URL and does a few things with them.
My issue is, I can’t seem to use document.location to show the specific value that I’m after, for example:
www.examplesite.com?yourname=gilgilad
I want to use document.location.search and put it in a var, I need that var's value to be "gilgilad".
Is this even possible using location.search?
location.search will return all after question mark including it. So there is universal js to get value of the first parameter (even if url has more parameters):
var desire = location.search.slice(1).split("&")[0].split("=")[1]
Example: let's take url http://example.com?name=jon&country=us
location.search will be equal to ?name=jon&country=us
.slice(1) skips the ?, returning the rest of the string.
.split("&")[0] splits it into two strings (name=jon and
country=us) and takes first one
.split("=")[1] splits name=jon into name and jon and takes the second one. Done!
let url = new URL('www.examplesite.com?yourname=gilgilad');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('yourname'));
you can consider also to user window.location or window.location.search directly
let searchParams = new URLSearchParams(window.location.search);
console.log(searchParams.get('yourname'));
A more generic solution to split the location.search query parameters and convert them into an object:
var a = location.search.split("&");
var o = a.reduce(function(o, v) {
var kv = v.split("=");
kv[0] = kv[0].replace("?", "");
o[kv[0]] = kv[1];
return o;
},
{});
To make ?yourname=gilgilad using document.location.search:
window.location.search = 'yourname=gilgilad';
here is jsfiddle: http://jsfiddle.net/t81k3bgc/
make sure to use console and then [run]. you will see:
For more information:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.235.3A_Send_a_string_of_data_to_the_server_by_modifying_the_search_property.3A

Passing in a key results in extra characters in my firebase URL, how do I remove them?

When placing the "key" variable inside of this string, it displays 'simplelogin%3A5' instead of 'simplelogin:5'. Is there a way to just pass in the latter?
var populateTasks = function(date, key){
$scope.ref = new Firebase("https://myfirebase.firebaseio.com/users/"+key+"/tasks");
};
results in: https://myfirebase.firebaseio.com/users/simplelogin%3A5/tasks
I need: https://myfirebase.firebaseio.com/users/simplelogin:5/tasks
var uri = "//what you need to convert";
var uri_dec = decodeURIComponent(uri);
var res = uri_dec;
Where does the value of key come from? If you get it from a URL, it makes sense that you see %3A.
A : has a special meaning in a URL, so it is escaped. And the URL escape sequence for a : is %3A.
To convert the %3A back to : you simply unescape it like this:
unescape(key)
Or use decodeURIComponent, which in this case accomplishes the same. The best way to decode the value depends on why it was encoded in the first place, hence my initial question.
Have you tried trimming key before concatenating it to the URL?
key = key.trim();

converting request.querystring using toString()

In JScript, why do I get the error "Object doesn't support this property or method" when I try to convert request.querystring to a string using toString()?
var params = Request.QueryString;
var params = params.toString();
Background info:
I'm trying to convert the querystring to a string so that I can perform a regex replace and remove certain items when they appear in the url.
var param = param.replace(/([?&])(allow)=[\w-]+/g, "");
I recently discovered the solution to this problem.
var params = Request.QueryString;
should be:
var params = Request.QueryString.Item;
There is no need to convert params to a string after that to manipulate the query string. Further you have access to everything in the query string by calling Request.QueryString("param").Item.
Example:
http://www.mysite.com?q=query&name=george
var name = Request.QueryString("name").Item;
I don't know -- weird Microsoft JScript implementation.
I had the same problem.
var strParams = new String(params);
seems to work though.

Categories