Get string from url using jQuery? - javascript

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.

Related

Converting a badly stringfied json to a json object

I have some data i am pulling from a web service. This is the string
(Body:'3886' MessageProperties [headers={}, timestamp=null,
messageId=null, userId=null, receivedUserId=null, appId=null,
clusterId=null, type=null, correlationId=null,
correlationIdString=null, replyTo=null,
contentType=application/x-java-serialized-object,
contentEncoding=null, contentLength=0, deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0,
redelivered=false, receivedExchange=,
receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62,
messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,
consumerQueue=bottomlesspit])
It looks like json but the key value pairs are almost fine but the most important key which is Body isn't like other keys as the string would tell.
I need to read the value of Body and be able to get the value like this
console.log(d.body);
//This above outputs the string as shown
obj = eval('{' + d.body + '}');
console.log(obj);
var match = "Body";
var val = obj.find( function(item) { return item.key == match } );
console.log(val);
How can i read the value of the key Body?.
Use this regular expression instead of a match Body:
\bBody:'(\d*)'
This will catch the Body number in group 1.
You can write a parser function get string and extract values. A very simple function is here. You can modify it also for all exceptions exist.
var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;
function f(inp) {
var index = str.indexOf(inp),
endIndex;
for(var i = index; i < str.length; i ++) {
if(str[i] == ',') {
endIndex = i;
break;
}
}
var output = str.substr(index, endIndex).split('=');
return output;
}
console.log(f('consumerQueue'));
Why not use a regex to match and extract the Body.
Example:
const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
const body = match[1] // This is the value of Body
} else {
// Unable to find Body, handle it here
}

Javascript get URL parameter that starts with a specific string

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

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

JS: Check Query String for GET variables that are not in an array?

Let's say I have an address of:
www.example.com/index.php?a=1&b=2&c=3
I want to enter that into an input field like this (value would obviously initially be blank):
<input id="my-input-field" value="www.example.com/index.php?a=1&b=2&c=3">
Then I want JS to parse everything after the ?, take all of the queries ("a", "b", "c") and see if they exist in an array().
Then I want to display a message stating that some of the items in the given URL were missing - but that's the easy part.
The part that I'm having trouble figuring out is: how to break down the URL and only find the first part of each query?
I understand how to strip everything before the question mark (including the question mark):
var str = "www.example.com/index.php?a=1&b=2&c=3";
str = str.substring(str.indexOf("?") + 1);
alert(str);
Fiddle: http://jsfiddle.net/xx3fwhvv/
This returns: a=1&b=2&c=3
The next step could be to split the string up per each &?
var str = "a=1&b=2&c=3";
str = str.split("&");
alert(str);
Fiddle: http://jsfiddle.net/3Lo24byo/
This returns: a=1,b=2,c=3
We can then remove everything after the ='s sign like this:
var str = 'a=1';
str = str.substring(0, str.indexOf('='));
alert(str);
Fiddle: http://jsfiddle.net/vfzvu5mh/
This results in: a
The thing now is how do I loop through the array and do this for each item? That would be the step I need to take.
Then I need to have an array like:
var myArray = array('a','c','d');
In the above array, cross checking the array that we created above to see if any of the values match up should return b as not matching up, as it's not in myArray.
This is where I'm stuck. Any help is appreciated. I'm not very good with JS but I've been working at this trying to figure it out.
All together so far, the code would look something like this:
var str = "www.example.com/index.php?a=1&b=2&c=3";
newStr = str.substring(str.indexOf("?") + 1);
strArray = newStr.split("&");
i = 1;
for {
newStrArray = strArray[i].substring(0, strArray[i].indexOf('='));
i++;
}
The above doesn't work for me, but something like that any way.
EDIT (I'll be actively editing this part until the question is answered):
var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
alert(myStringArray[i]);
}
Current Fiddle: https://jsfiddle.net/03ho0nbz/
First off, you're overwriting your array with the result of a substring:
myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
myStringArray receives the results of the substring, turning it into a string.
To compare myArray with otherArray and see if an element not exists in myArray you can use the indexOf() function:
var myArray = ['a', 'c', 'd'];
var otherArray = ['a', 'b', 'c'];
for(var i=0;i<otherArray.length;i++) {
if(myArray.indexOf(otherArray[i]) === -1) {
console.log('myArray does not have', otherArray[i]); // myArray does not have b
}
}
Going by your example this would create a loop looking something like:
var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var myArray = ['a', 'c', 'd'];
for (var i = 0; i < myStringArray.length; i++) {
var eqIndex = myStringArray[i].indexOf('=');
if(eqIndex !== -1) {
var key = myStringArray[i].substring(0, eqIndex);
if(myArray.indexOf(key) === -1) {
alert(key, "not in myArray!");
}
}
}
Note that this way of writing JS is fine for learning practices, but if you intend to use JS in a professional setting, please read up on some JS good practices.
What i would do is to fiddle around with JS like you're doing, try and see if you can buy some JS good practices books and also look at how popular frameworks solve things. For professional purpose it's almost always a good idea to use a framework that's well maintained and supported. For example if you would use underscore in this case you could do something like:
var paramKeys = _.chain("a=1&b=2&c=3".split('&')).map(function(params) {
var p = params.split('=');
return p[0];
}).value();
_.difference(paramKeys, ['a', 'c', 'd']) // "b"
#mattroberts33 I am unable to understand why you are checking first parameter in the url, is there anything deference from www.example.com/index.php?a=1&b=2&c=3 to www.example.com/index.php?b=2&a=1&c=3. I would encourage read parameters based on the keys instead of index. In any url query parameters might jumbled.
Below method will return parameter by passing key and url to the method:
var getParameterByName = function (name, url) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
if (url) {
var results = regex.exec(url);
} else {
var results = regex.exec(location.search);
}
return results == null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));};
If you still wants to get based on index we can modify above method, But that is not encouraging.

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