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

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

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

How to detect pagelinks in URL [duplicate]

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

Get a specific string of numbers inside an url

So here we have some url's from same domain:
http://example.com/video6757788/sometext
http://example.com/video24353/someothertext
http://example.com/video243537786/somedifferenttext
http://example.com/video759882
http://example.com/video64353415
http://example.com/video342432?session=somestring
How to get just the numbers part that comes after video in all types of the url's. I'm trying to get the video id's.
First i get the url's, but then how do I get the id's?
var url = $('a[href*="example"]');
var id = ???
Use a regular expression:
$('a[href*="example"]').each(function() {
var $this = $(this);
var url = $this.attr("href");
var id = url.match(/video(\d+)/i)[1]; //retrieve the number following video*
//logic
})
Or if you want to be fancy with .attr(), equivalent would be:
$('a[href*="example"]').attr("href", function(indx, url) {
var id = url.match(/video(\d+)/i)[1]; //retrieve the number following video*
//logic
})

Javascript: save way to read GET without PHP

I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.

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

Categories