Javascript get URL parameter that starts with a specific string - javascript

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

Related

Getting query string parameters from clean/SEO friendly URLs with JavaScript

I've recently switched my site to use clean/SEO-friendly URLs which has now caused me some issues with a JavaScript function I had for grabbing the query string parameters.
Previously I had been using this function:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
Which worked fine on things like this as you could just call getQueryVariable("image") and return "awesome.jpg".
I've been playing with the indexOf(); function to try and grab the relevant parameters from the current URL, eg:
var url = window.location.pathname;
var isPage = url.indexOf("page") + 1;
In an attempt to get the array index number of the "page" parameter, and then plus 1 it to move along to the value of that (?page=name > /page/name/)
JavaScript isn't my main language, so I'm not used to working with arrays etc and my attempt to turn this into a new function has been giving me headaches.
Any pointers?
How about something like this? It splits the path and keeps shifting off the first element of the array as it determines key/value pairs.
function getPathVariable(variable) {
var path = location.pathname;
// just for the demo, lets pretend the path is this...
path = '/images/awesome.jpg/page/about';
// ^-- take this line out for your own version.
var parts = path.substr(1).split('/'), value;
while(parts.length) {
if (parts.shift() === variable) value = parts.shift();
else parts.shift();
}
return value;
}
console.log(getPathVariable('page'));
This can be done formally using a library such as router.js, but I would go for simple string manipulation:
const parts = '/users/bob'.split('/')
const name = parts[parts.length - 1] // 'bob'

How to find url parameter # with value in javascript

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

Count the number of parameters in query string

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

Get string from url using jQuery?

Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.

Get query string parameters url values with jQuery / Javascript (querystring)

Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:
$('?search').val();
Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.
I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.
After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!
//Assuming URL has "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?
post=1234&action=edit&active=1"
UPDATE : IE is not supported
use this function from an answer below instead of URLSearchParams
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('action')); //edit
Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
http://jsfiddle.net/gilly3/sgxcL/
An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):
location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
if (pair === "") return;
var parts = pair.split("=");
location.queryString[parts[0]] = parts[1] &&
decodeURIComponent(parts[1].replace(/\+/g, " "));
});
http://jsfiddle.net/gilly3/YnCeu/
This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.
JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use
$.url().param('search');
This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.
Or you can use js-url instead. Its quite similar to the one below.
So you can access the query param like $.url('?search')
Found this gem from our friends over at SitePoint.
https://www.sitepoint.com/url-parameters-jquery/.
Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.
//URL is http://www.example.com/mypage?ref=registration&email=bobo#example.com
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //bobo#example.com
Use as you will.
This isn't my code sample, but I've used it in the past.
//First Add this to extend jQuery
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
//Second call with this:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its name
var byName = $.getUrlVar('name');
I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:
function getParameterByName( name ){
var regexS = "[\\?&]"+name+"=([^&#]*)",
regex = new RegExp( regexS ),
results = regex.exec( window.location.search );
if( results == null ){
return "";
} else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
// example caller:
var result = getParameterByName('Mode');
Building on #Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).
function parseQueryString () {
var parsedParameters = {},
uriParameters = location.search.substr(1).split('&');
for (var i = 0; i < uriParameters.length; i++) {
var parameter = uriParameters[i].split('=');
parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
}
return parsedParameters;
}
function parseQueryString(queryString) {
if (!queryString) {
return false;
}
let queries = queryString.split("&"), params = {}, temp;
for (let i = 0, l = queries.length; i < l; i++) {
temp = queries[i].split('=');
if (temp[1] !== '') {
params[temp[0]] = temp[1];
}
}
return params;
}
I use this.
Written in Vanilla Javascript
//Get URL
var loc = window.location.href;
console.log(loc);
var index = loc.indexOf("?");
console.log(loc.substr(index+1));
var splitted = loc.substr(index+1).split('&');
console.log(splitted);
var paramObj = [];
for(var i=0;i<splitted.length;i++){
var params = splitted[i].split('=');
var key = params[0];
var value = params[1];
var obj = {
[key] : value
};
paramObj.push(obj);
}
console.log(paramObj);
//Loop through paramObj to get all the params in query string.
function getQueryStringValue(uri, key) {
var regEx = new RegExp("[\\?&]" + key + "=([^&#]*)");
var matches = uri.match(regEx);
return matches == null ? null : matches[1];
}
function testQueryString(){
var uri = document.getElementById("uri").value;
var searchKey = document.getElementById("searchKey").value;
var result = getQueryStringValue(uri, searchKey);
document.getElementById("result").value = result;
}
<input type="text" id="uri" placeholder="Uri"/>
<input type="text" id="searchKey" placeholder="Search Key"/>
<Button onclick="testQueryString()">Run</Button><br/>
<input type="text" id="result" disabled placeholder="Result"/>

Categories

Resources