Get values of parameters from URL - javascript

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

Related

Regex for url line [duplicate]

This should be very simple (when you know the answer). From this question
I want to give the posted solution a try. My question is:
How to get the parameter value of a given URL using JavaScript regular expressions?
I have:
http://www.youtube.com/watch?v=Ahg6qcgoay4
I need:
Ahg6qcgoay4
I tried:
http://www.youtube.com/watch\\?v=(w{11})
But: I suck...
You almost had it, just need to escape special regex chars:
regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
Edit: Fix for regex by soupagain.
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
Not tested but this should work:
/\?v=([a-z0-9\-]+)\&?/i
v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk
In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString
HttpUtility.ParseQueryString(url)["v"];
And you don't even need to check the key, as it will return null if the key is not in the collection.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
DEMO
I use seperate custom functions which gets all URL Parameters and URL parts .
For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The above function will return an array consisting of url variables.
For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b
I use a simple uri split,
function getUrlParams() {
var vars = {};
var parts = window.location.href.split('/' );
return parts;
}
You can even combine them both to be able to use with a single call in a page or in javascript.

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

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

Get the url Parameter string from Javascript

I need the whole parameter list as such , not one by one
var Url = "http://localhost/Home/Admin?param1=1&param2=2$param3=3";
I want to get the whole parameter list from the url.
var params = "param1=1&param2=2&param3=3";
var Url = "http://localhost/Home/Admin?param1=1&param2=2$param3=3";
var urlArray = url.split("?");
var params=urlArray[1];
You can see Using split() example of Mozilla Developer Network for more insight on using the split function.
Thanks for the support, I use this one for my need
var params = window.location.href.split('?')[1];

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

Remove querystring parameters from url with regex

I'm pretty new to regex and need to remove some content from our url
http://mysite.blah/problem/smtp/smtp-open-relay?page=prob_detail&showlogin=1&action=smtp:134.184.90.18
I need to remove everything from the "?" and on, leaving me just:
http://mysite.blah/problem/smtp/smtp-open-relay
Here is our current regex expression we are using to grab the route data. For example I can grab "smtp" and "smtp-open-relay" (which we need). However sometimes our url changes depending on where the user is coming from thereby appending the querystring parameters which is causing our current regex expression to blow up.
// Retrieve the route data from the route
var routeData = /([0-9a-zA-Z_.-]+)\/([0-9a-zA-Z_.-]+)$/g.exec(route);
I need it to ignore stuff from the "?" on.
A regular expression is probably more than you need.
You could do the following to remove the ? and everything (query
string + hash) after it:
var routeData = route.split("?")[0];
If you truly wanted to strip only the query string, you could preserve
the hash by reconstructing the URL from the window.location object:
var routeData = window.location.origin + window.location.pathname + window.location.hash;
If you want the query string, you can read it with window.location.search.
i just used this one
var routeData= route.substring(0, route.indexOf('?'));
Use this function:
var getCleanUrl = function(url) {
return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};
// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
If you're doing this in-browser, let the browser do the parsing:
location.origin + location.pathname
Or for arbitrary URLs:
function withoutQS(_url) {
var url = document.createElement('a');
url.href = _url;
return url.origin + url.pathname;
}
Following is the cleaner way to remove a given parameter say: prop1 form querystring of url.
Querystring can be found in url by accessing
window.location.search
Here you apply regular expression for prop1:
var queryStringWithoutProp1=window.location.search.replace(/(&?prop1=)(.[^&]*)/,"");
queryStringWithoutProp1 must return querystring without prop1=value parameter-value combination from querystring
Note: '&?' ensures whether prop1 appears as first parameter or any subsequent one.

Categories