How can I count the number of parameters query strings passed? e.g.
www.abc.com/product.html?product=furniture&&images=true&&stocks=yes
I want to be able to get the answer as 3
1. product=furniture
2. images=true
3. stocks=yes
var url = window.location.href;
var arr = url.split('=');
console.log(url.length)
You can use String's match:
var matches = str.match(/[a-z\d]+=[a-z\d]+/gi);
var count = matches? matches.length : 0;
first get the location of a question mark character ? in the required url
var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);
then get the array of parameters:
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
Then count the length of result as
result.length;
If you're using express you can use
Object.keys(req.query).length
see here: How to get number of request query parameters in express.js?
You could use the search variable in the document.location object to get the search string and then use a match on the '=' symbols to get a count (see example below)
var paramCount = document.location.search.match(/=/g).length;
How about the URLSearchParams interface that provides utility methods to work with the query string of a URL?
Something like that:
var url_string = window.location.href;
var url_var = new URL(url_string);
var params = url_var.searchParams;
var param_count = 0;
for (const [key, value] of params.entries()) {param_count++;}
Related
With javascript, I'd like to return any url parameter(s) that start with Loc- as an array. Is there a regex that would return this, or an option to get all url parameters, then loop through the results?
Example: www.domain.com/?Loc-chicago=test
If two are present in the url, I need to get both, such as:
www.domain.com/?Loc-chicago=test&Loc-seattle=test2
You can use window.location.search to get all parameters after (and including ?) from url. Then it's just a matter of looping through each parameter to check if it match.
Not sure what kind of array you expect for result but here is very rough and basic example to output only matched values in array:
var query = window.location.search.substring(1);
var qsvars = query.split("&");
var matched = qsvars.filter(function(qsvar){return qsvar.substring(0,4) === 'Loc-'});
matched.map(function(match){ return match.split("=")[1]})
Use URLSearchparams
The URLSearchParams interface defines utility methods to work with the
query string of a URL.
var url = new URL("http://" + "www.domain.com/?Loc-chicago=test&NotLoc=test1&Loc-seattle=test2");
var paramsString = url.search;
var searchParams = new URLSearchParams(paramsString);
for (var key of searchParams.keys()) {
if (key.startsWith("Loc-")) {
console.log(key, searchParams.get(key));
}
}
Here is a function you can use that accepts a parameter for what you are looking for the parameter to start with:
function getUrlParameters(var matchVal) {
var vars = [];
var qstring = window.location.search;
if (qstring) {
var items = qstring.slice(1).split('&');
for (var i = 0; i < items.length; i++) {
var parmset = items[i].split('=');
if(parmset[0].startsWith(matchVal)
vars[parmset[0]] = parmset[1];
}
}
return vars;
}
I need to find url parameter # with value in javascript.
my url is like:
http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer
i want to find this value #sid53239948
I find this How can I get query string values in JavaScript?
but how to find this value in url?
EDIT:
This will filter the sid into the sid-variable wherever you put your hash.
var url_arr = window.location.hash.split('&'),
sid = '';
url_arr.filter(function(a, b) {
var tmp_arr = a.split('#')
for (var i in tmp_arr)
if (tmp_arr[i].substring(0, 3) == 'sid')
sid = tmp_arr[i].substring(3, tmp_arr[i].length)
});
console.log(sid) // Will output '53239948'
Old answer:
var hash_array = window.location.hash.split('#');
hash_array.splice(0, 1);
console.log(hash_array);
use this plugin that help you to find exact information
https://github.com/allmarkedup/purl
Try this way,
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
// console.log(window.location.href);
// console.log(hashes);
for(var index = 0; index < hashes.length; index++)
{
var hash = hashes[index].split('=');
var value=hash[1];
console.log(value);
}
http://www.w3schools.com/jsref/jsref_indexof.asp
Search a string for "welcome":
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
The result of n will be:13. Maybe this helps you. In the posted link in your question you see how you get the url. But be careful: indexOf only returns the 1st occurence.
The post you have referenced is looking for a URL parameter in a string. These are indicated by:
?{param_name}={param_value}
What you are looking for is the anchor part of the URL or the hash.
There is a simple Javascript function for this:
window.location.hash
Will return:
#sid53239948
See reference:
http://www.w3schools.com/jsref/prop_loc_hash.asp
However, given a URL that has multiple hashes (like you one you provided), you will need to then parse the output of this function to get the multiple values. For that you will need to split the output:
var hashValue = window.location.hash.substr(1);
var hashParts = hashValue.split("#");
This will return:
['sid53239948', '%kjimwer']
Since you have hash values in query params, window.location.hash will not work for you. You can try to create an object of query parameters and then loop over them and if # exists, you can push in a array.
Sample
function getQStoObject(queryString) {
var o = {};
queryString.substring(1).split("&").map(function(str) {
var _tmp = str.split("=");
if (_tmp[1]) {
o[_tmp[0]] = _tmp[1];
}
});
return o
}
var url = "http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer";
// window.location.search would look like this
var search = "?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer";
var result = getQStoObject(search);
console.log(result)
var hashValues = [];
for(var k in result){
if(result[k].indexOf("#")>-1){
hashValues.push(result[k].split('#')[1]);
}
}
console.log(hashValues)
`
This solution will return you both values following #.
var url = 'http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer';
var obj = url.split('?')[1].split('&');
for(var i = 0; i < obj.length; i++) {
var sol = obj[i].split('#');
if(sol[1]) {console.log(sol[1]);}
}
I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}
www.domain.com/lookbook.html#look0&product1
On page load I would like to grab the whole hash ie. #look0&product1
then split it up and save the number of the look ie 0 in a variable called var look and the number of the product ie 1 in another variable called var product. Not sure how to achieve this.
Is this also the best way of passing and retrieving such parameters? Thanks
Use var myHash = location.hash to get hash part of URL. Than do var params = myHash.split('&') and after that for each part do part.split('=') to get key-value pairs.
Maybe it's better to pass these parameters via GET from PHP side and than post them inside page when page is processed via PHP?
<input type="hidden" name="look" value="<?php echo isset($_GET['look']) ? $_GET['look'] : '';?>"/>
Here's the pure Javascript method:
function parseHash(hash) {
// Remove the first character (i.e. the prepended "#").
hash = hash.substring(1, hash.length);
// This is where we will store our properties and values.
var hashObj = {};
// Split on the delimiter "&" and for each key/val pair...
hash.split('&').forEach(function(q) {
// Get the property by splitting on all numbers and taking the first entry.
var prop = q.split(/\d/)[0];
// Get the numerical value by splitting on all non-numbers and taking the last entry.
var val_raw = q.split(/[^\d]/);
var val = val_raw[val_raw.length - 1]
// If the property and key are defined, add the key/val pair to our final object.
if (typeof prop !== 'undefined' && typeof val !== 'undefined') {
hashObj[prop] = +val;
}
});
return hashObj;
}
Use like:
parseHash(window.location.hash /* #book10&id1483 */)
/* returns: Object {book: 10, id: 1483} */
I suggest using the norm for passing values through the location's hash: prop=value. Ex: #book=10&id=311. Then you can easily split on = for each property.
You can use .match(re) method with use of regular expression to extract the number from the given string.
You can try this:
var hashes = location.hash.split('&'); // get the hash and split it to make array
var values = hashes.map(function(hash){ // use .map to iterate and get a new array
return hash.match(/\d+/)[0]; // returns the numbers from the string.
});
var loc = "look0345345345&product1";
var hashes = loc.split('&');
var values = hashes.map(function(hash){ return hash.match(/\d+/)[0]; });
document.body.innerHTML = '<pre>'+ JSON.stringify(values) + '</pre>';
You could try this:
var url = 'www.domain.com/lookbook.html#look0&product1'
, result = {}
, expr = RegExp(/[#&]([a-zA-z]+)(\d+)/g);
var parts = expr.exec(url);
while(parts != null && parts.length == 3) {
result[parts[1]] = parts[2];
parts = expr.exec(url);
}
var look = result['look']
, product = result['product'];
document.getElementById('result').innerHTML = 'look = ' + look + '<br>' + 'product = ' + product;
<p id='result'></p>
We are basically using a regular expression to divide the parameter name and value into two groups that we can then get by calling expr.exec(url).
Each time we call expr.exec(url), we get the next set of name and value groups.
We set the value of the parameter to its name in the result object.
In the regular expression /[#&]([a-zA-z]+)(\d+)/g, the g after the /.../ means match each time find the two groups.
The two groups are prefaced by either & or # ([#&]). The first group is a String of letters ([a-zA-z]+), the name of the parameter. The second is a String of numbers (\d+), the value you are looking for.
The regex returns the String that matches the pattern as the first result in the parts array, followed by the groups matched, which which means that our two groups in each iteration will be parts[1] and parts[2].
you should use:
function parseHash(hash){
hash = hash.substring(1, hash.length); //remove first character (#)
var obj ={}; //create the output
var qa = hash.split('&'); //split all parameters in an array
for(var i = 0; i < qa.length; i++){
var fra1 = qa[i].split('='); //split every parameter into [parameter, value]
var prop = fra1[0];
var value = fra1[1];
if(/[0-9]/.test(value) && !isNaN(value)){ //check if is a number
value = parseInt(value);
}
obj[prop] = value; //add the parameter to the value
}
return obj;
}
document.querySelector("input.hash").onkeyup = function(){
console.log( parseHash(document.querySelector("input.hash").value));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="hash"/>
<p class="output"></p>
use as
parseHash(location.hash /* #look=0&product=1 );
/returns {look: 0, product: 1}/
I have a URL that includes a product ID which can be in the following format:
One alphabetical letter followed by a number of any number of digits, then an underscore, and then any number of digits and underscores.
So this is a valid product id: c23_02398105 and so is this: c23_02398105_9238714.
Of course in a URL, it's sandwiched between other query string items, so in this url, i want to extract just the id:
http://www.mydomain.com/product.php?action=edit&id=c23_02398105&side=1
I've been trying a regex something along the lines of this, to no avail:
/&id=[a-z]_[(0-9)*]&/
What's the correct way to extract the product id?
function qry(sr) {
var qa = [];
for (var prs of sr.split('&')) {
var pra = prs.split('=');
qa[pra[0]] = pra[1];
}
return qa;
}
var z = qry('http://example.com/product.php?action=edit&id=c23_02398105&side=1');
z.id; // c23_02398105
Source
The below returns an array of values for each key, so if you wanted to get a string for the below, join the values with some delimiter (eg params.id.join(',')) to get your comma-delimited string of IDs.
See Fiddle
http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash
Handles:
Regular key/value pair (?param=value)
Keys w/o value (?param : no equal sign or value)
Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
Repeated Keys (?param=1¶m=2)
Removes Empty Keys (?&& : no key or value)
Code:
function URLParameters(_querystring){
var queryString = _querystring || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/^[^?]*\?/,''); // only get search path
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
if (! (!isNaN(parseFloat(pairNum)) && isFinite(pairNum)) ) continue;
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
How to Call:
var params = URLParameters(<url>); // if url is left blank uses the current page URL
params.key; // returns an array of values (1..n) for the key (called 'key' here)
Example Output for Given Keys ('key','keyemptyvalue','keynovalue') using Above URL:
key ["value"]
keyemptyvalue [""]
keynovalue [undefined, "nowhasvalue"]
You can use JavaScript string functions instead of regexp like this:
var url = "http://www.example.com/product.php?action=edit&id=c23_02398105&side=1";
var idToEnd = url.substring(url.search("&id")+4, url.length);
var idPure = idToEnd.substring(0, idToEnd.search("&"));
alert(idPure);
the output is c23_02398105
The following expression fits your description
/&id=([a-z]\d*_[\d_]*)/
It assumes that the letter is lower-case, and that there is only one id in the url in the specified format, or that the one you want is the first one.
var url =
'http://www.mydomain.com/product.php?action=edit&id=c23_02398105&side=1';
var m = url.match( /&id=([a-z]\d*_[\d_]*)/ );
console.log( m && m[1] ); // 'c23_02398105'