How to detect pagelinks in URL [duplicate] - javascript

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

Related

Getting URL parameters and filter out a specific parameter

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

get many #hash values in url (anchor) in jquery

i try to get values of a url with anchor like this: http://website/list/#/genre/song
It is in jquery because after i get the values, i have to edit html tags contents.
I retrieve hash value with:
var hash = window.location.hash.substring(1);
I have 2 variables:
var genre;
var song;
the problem is that there may be 2 possibilities in the url:
http://website/list/#/genre or http://website/list/#/genre/
or
http://website/list/#/genre/song or http://website/list/#/genre/song/
if we are in case 1, i would have 'genre' value from hash variable
if we are in case 2, i would have 'genre' and 'song' values from hash variable
my jquery function is actually simple:
$(function(){
var hash = window.location.hash.substring(1);
var url_parts = hash.replace(/\/\s*$/,'').split('/');
console.log("result: "+url_parts);
});
I do not know how to consider the two cases. Actually i just get a full string.
And if i try http://website/list/#/genre/, the result is:
result: ,genre
can you help me?
Test whether a particular index exists after splitting:
$(function(){
var hash = window.location.hash.substring(1);
var url_parts = hash.replace(/\/\s*$/,'').split('/');
genre = url_parts.length >= 2 ? url_parts[1] : '';
song = url_parts.length >= 3 ? url_parts[2] : '';
console.log("result: "+url_parts);
});

How do I get the fragment identifier (value after hash #) from a URL?

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

Difficulty writing a function to extract URL from array

I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];

How to get "GET" request parameters in JavaScript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
How to get "GET" variables from request in JavaScript?
Does jQuery or YUI! have this feature built-in?
Update June 2021:
Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).
Original:
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
You could use jquery.url I did like this:
var xyz = jQuery.url.param("param_in_url");
Check the source code
Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser
try the below code, it will help you get the GET parameters from url .
for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
Just to put my two cents in, if you wanted an object containing all the requests
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
var QueryString = getRequests();
//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3
Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.
function Request(name){
return QueryString[name.toLowerCase()];
}
Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:
var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)
You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.
If you already use jquery there is a jquery plugin that handles this:
http://plugins.jquery.com/project/query-object
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
Works for me in
url: http://localhost:8080/#/?access_token=111
function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}

Categories