For example, I have this URL:
http://www.shafadoc.ir/#!mykey=ali
how can get the value of mykey?
If you only have one parameter you can do that:
var param = location.search.split('mykey=')[1]
EDIT:
This is probably better:
var param = window.location.hash.substr(1);
Related
I have the URL:
http://www.sampleurl.com/entrant-entry?entry=ca2f346b12cabcf2626b81c6900500ff
I need to take the value of entry, which in this case is ca2f346b12cabcf2626b81c6900500ff and attach it to the end of the destination URL:
http://ugc-4vets4life.market-online.net/voter-entry?entry=ca2f346b12cabcf2626b81c6900500ff
I have looked at several answers but none seem to make it clear to me. I need to do this in JavaScript.
Something like this:
var url_string = "http://www.sampleurl.com/entrant-entry?entry=ca2f346b12cabcf2626b81c6900500ff";
var voter_url_string = "http://ugc-4vets4life.market-online.net/voter-entry?entry=";
var url = new URL(url_string);
var entry = url.searchParams.get("entry");
var final_url_string = voter_url_string + entry;
console.log(final_url_string);
I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
Here is the URL :
www.example.com/?param%5B%5D=A¶m%5B%5D=B
the %5B%5D part is [] to pass param as an array, which is encoded in url.
Now, I want to remove one of parameters , desired output is:
www.example.com/?param%5B%5D=B
I have searched for this but found nothing!
All the answers are about removing a single value parameter, not multiple.
UPDATE:
I don't know the exact position of the parameter, i.e the URL could be something like this:
www.example.com/?test=124&test2=456¶m%5B%5D=A¶m%5B%5D=B
You can take advantage of URL WebAPI.
https://developer.mozilla.org/en-US/docs/Web/API/URL
var base = 'http://www.example.com/'
var query = '?param%5B%5D=A¶m%5B%5D=B';
var url = new URL(base + query);
var params = new URLSearchParams(url.search);
var filteredParams = params.getAll('param[]')
.filter(function(el) {
return el !== "A";
}).map(function(el){
return ['param[]', el];
});
var newParams = new URLSearchParams(filteredParams);
var url = new URL(base + '?' + newParams.toString() );
console.log(url.toString());
Here is an example on how to extract the params from the URL.
Now how to use them on a user user interaction form (UI) is up to you.
// Use this to get the document location:
var ActualURL = document.location.href;
console.log("This snippet URL: "+ActualURL);
// Only for this demo, I "simulate" a URL.
// ActualURL is overwritten here.
var ActualURL = "www.example.com/?param%5B%5D=A¶m%5B%5D=B";
console.log("FAKED URL: "+ActualURL);
var domain = ActualURL.split("?")[0];
console.log("Domain: "+domain);
var params = ActualURL.split("?")[1];
var param_array = params.split("&");
for (i=0;i<param_array.length;i++){
console.log( "Param #"+i+": "+param_array[i] );
}
console.log("Rebuilted URL with only param #2: "+domain+"?"+param_array[1]);
In Javascript, how can I get the parameters of a URL string (not the current URL)?
http://localhost:8080/feasthunt/changePassword.html?TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED
can i get token in JSON object?
No need for a 'JSON' object, and just use split to grab it, since its after a '='
var url = 'http://localhost:8080/feasthunt/changePassword.html? TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED';
var token = url.split('=').pop();
//token is equal to: "0FA3267F-0C62-B1C9-DB71-76F6829671ED"
https://jsbin.com/siyazo/1/edit?js,console
try this
var str = "http://localhost:8080/feasthunt/changePassword.html?TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED";
var tokenValue = str.substring(str.indexOf("?")+1).split("=")[1];
Or more generic
var paramMap = {}; str.substring(str.indexOf("?")+1).split("&").forEach(function(val){
var param = val.split("=");
paramMap[param[0]] = param[1];
})
paramMap is your JSON object, where paramMap["TOKEN"] will give you the value for this param
Example:
www.site.com/index.php#hello
Using jQuery, I want to put the value hello in a variable:
var type = …
No need for jQuery
var type = window.location.hash.substr(1);
Since String.prototype.substr is deprecated use substring instead.
var type = window.location.hash.substring(1);
You may do it by using following code:
var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);
SEE DEMO
var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
hash = type[1];
alert(hash);
Working demo on jsfiddle
Use the following JavaScript to get the value after hash (#) from a URL. You don't need to use jQuery for that.
var hash = location.hash.substr(1);
I have got this code and tutorial from here - How to get hash value from URL using JavaScript
It's very easy. Try the below code
$(document).ready(function(){
var hashValue = location.hash.replace(/^#/, '');
//do something with the value here
});
I had the URL from run time, below gave the correct answer:
let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);
hope this helps
Get fragment of current document location
var hash = window.location.hash;
Get fragment from string
// absolute
var url = new URL('https://example.com/path/index.html#hash');
console.log(url.hash);
// relative (second param is required, use any valid URL base)
var url2 = new URL('/path/index.html#hash2', 'http://example');
console.log(url2.hash);
Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...
// Helper Method Defined Here.
(function (helper, $) {
// This is now a utility function to "Get the Document Hash"
helper.getDocumentHash = function (urlString) {
var hashValue = "";
if (urlString.indexOf('#') != -1) {
hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
}
return hashValue;
};
})(this.helper = this.helper || {}, jQuery);