Get Parameter from URL and use it in dictionary - javascript

i have basically 0 programming experience. So here is my question. I am Using a JS to get some Parameters from URL and use it with the HTML, and it works.
This is the code:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
and in HTML
<script type="text/javascript">document.write(qs("name"));</script>
Now, let's say I want to use the Value of the Parameters to generate a specific Text on the page. But I do not want to use the Parameter itself, but rather use a kind of Dictionary, to match a Parameter to a String.
for Example
a1 : "Good morning"
b2 : "Good evening"
I have tried something linke this, with no success, can someone help?:
function qs(search_for) {
var dict = {}
dict[a1] = "Good morning";
dict[b2] = "Good evening";
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
if parms[i].substring(pos+1) in dict {
return dict[parms[i].substring(pos+1)];;
}
}
}
return "";
}
Thanks in advance!
L
EDIT: Just to be clear, I do not want to read Parameters "a1" and "b2". I rather want that when a certain Parameter equals "a1" the function returns "Good morning" and when a certain parameter equals "b2" the function returns "Good evening"

You do this:
function getParam(param){
var both = location.search.replace('?', '').split('&');
for(var i=0,a,l=both.length; i<l; i++){
a = both[i].split('=');
if(a[0] === encodeURIComponent(param)){
return decodeURIComponent(a[1]);
}
}
return undefined;
}
var useInDict = getParam('a1');
Assumes raw url encode.

function parseGETfromUrl ( query = location.search.substring( 1 ) ) {
let parameters = {};
for ( const [ name, value ] of new URLSearchParams( query ) ) parameters[name] = value;
return parameters;
}
//Test code
let paramsString = "q=URLUtils.searchParams&topic=api";
parseGETfromUrl( paramsString ); // { q: "URLUtils.searchParams", topic: "api" }
parseGETfromUrl(); //Same result as above, when url ends with "?q=URLUtils.searchParams&topic=api"
Heading function parseGETfromUrl returns an object which contains information of url query string.

Related

I need to get the last two value after dot using javascript split

I am getting the results like demo.in,demo.co.in,demo.tv,demo.org.in
I need to split the extension separately using JavaScript split function
var vsp = i.split(".");
this is my code I will get the result as
demo,in demo,co,in
but I need to get the extension separately
Working fiddle(demo version)
var values = [
"demo.in",
"demo.co.in",
"demo.tv","demo.org"
];
var results = [];
// iterate through the values
for (var i = 0, len = values.length; i < len; i++) {
// Split the parts on every dot.
var parts = values[i].split(".");
// Remove the first part (before the first dot).
parts = parts.slice(1, parts.length);
// Join the results together
results.push(parts.join("."));
};
console.dir(results); // all done
// Nicely display the values for the OP:
for (var i = 0, len = results.length; i < len; i++) {
document.body.innerHTML += (i + 1) + ": " + results[i] + "<br />";
};
I have no idea what you want, so here's some functions to cover the likely cases:
var s = 'demo.co.in'
// Return everything before the first '.'
function getExtension(s) {
var m = s.match(/^[^.]+/);
return m? m[0] : '';
}
alert(getExtension(s)); // demo
// Return everything after the last '.'
function getExtension2(s) {
var m = s.match(/[^.]+$/);
return m? m[0] : '';
}
alert(getExtension2(s)); // in
// Return everything after the first '.'
function getExtension3(s) {
return s.replace(/^[^.]+\./, '');
}
alert(getExtension3(s)); // co.in
I could not understand exactly .. "the extension" . You can try like below code
var urls = "demo,demo.in,my.demo.co.in,demo.tv,demo.org.in"
.split(',');
var splited = urls.reduce( function( o, n ){
var parts = n.split( '.' );
o[ n ] = (function(){
var ext = [];
while( !(parts.length == 1 || ext.length == 2) ) {
ext.unshift( parts.pop() );
};
return ext.join('.');
}());
return o;
}, {} );
console.log( JSON.stringify( splited ) );
which prints
{
"demo":"",
"demo.in":"in",
"my.demo.co.in":"co.in",
"demo.tv":"tv",
"demo.org.in":"org.in"
}
process result using
for( var i in splited ) {
console.log( i, splited[i]);
}
Try this:
var vsp = i.split(".");
for(var i=0; i< vsp.length; i++){
if(i !== 0){ //leaving the first match
// do something with vsp[i]
}
}
I hope you are not considering www also. :). If so, then keep i>1 instead of i !== 0.
There are several ways to do it (probably none as easy as it should be). You could define a function like this:
function mySplit(str, delim) {
var idx = (str.indexOf(delim) == -1) ? str.indexOf(delim) : str.length;
return [str.substr(0,idx), str.substr(idx)];
}
And then call it like: var sp = mySplit(i, ".");
You can also use lastIndexOf, which returns the location of the last . and from there you can get the rest of the string using substring.
function getExtension(hostName) {
var extension = null;
if(hostName && hostName.length > 0 && hostName.indexOf(".") !== -1) {
extension = hostName.substring(hostName.lastIndexOf(".") + 1);
}
return extension;
}
From there, you can use this function in a loop to get the extensions of many host names.
Edit Just noticed the "last two values" part in the title :) Thanks #rab

Javascript Function to split and return a value from a string

I am trying to grab a certain value. I am new to javascript and I can't figure out why this is not working.
If I parse "kid_2" I should get "kostas". Instead of "Kostas" I always get "02-23-2000". So I must have a logic problem in the loop but I am really stuck.
function getold_val(fieldname,str){
var chunks=str.split("||");
var allchunks = chunks.length-1;
for(k=0;k<allchunks;k++){
var n=str.indexOf(fieldname);
alert(chunks[k]);
if(n>0){
var chunkd=chunks[k].split("::");
alert(chunkd);
return chunkd[1];
}
}
}
var test = getold_val('kid_2','date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||');
alert(test);
A regex may be a little more appealing. Here's a fiddle:
function getValue(source, key){
return (new RegExp("(^|\\|)" + key + "::([^$\\|]+)", "i").exec(source) || {})[2];
}
getValue("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","kid_2");
But if you want something a little more involved, you can parse that string into a dictionary like so (fiddle):
function splitToDictionary(val, fieldDelimiter, valueDelimiter){
var dict = {},
fields = val.split(fieldDelimiter),
kvp;
for (var i = 0; i < fields.length; i++) {
if (fields[i] !== "") {
kvp = fields[i].split(valueDelimiter);
dict[kvp[0]] = kvp[1];
}
}
return dict;
}
var dict = splitToDictionary("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","||","::");
console.log(dict["date_1"]);
console.log(dict["date_2"]);
console.log(dict["kid_1"]);
console.log(dict["kid_2"]);​
This works, here's my fiddle.
function getold_val(fieldname,str) {
var chunks = str.split('||');
for(var i = 0; i < chunks.length-1; i++) {
if(chunks[i].indexOf(fieldname) >= 0) {
return(chunks[i].substring(fieldname.length+2));
}
}
}
alert(getold_val('kid_2', 'date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||'));
The issue with your code was (as #slebetman noticed as well) the fact that a string index can be 0 because it starts exactly in the first letter.
The code is almost the same as yours, I just didn't use the second .split('::') because I felt a .substring(...) would be easier.
There are two bugs. The first error is in the indexOf call:
var n = str.indexOf(fieldname);
This will always return a value greater than or equal to 0 since the field exists in the string. What you should be doing is:
var n = chunks[k].indexOf(fieldname);
The second error is in your if statement. It should be:
if(n >= 0) {
...
}
or
if(n > -1) {
...
}
The substring you are looking for could very well be the at the beginning of the string, in which case its index is 0. indexOf returns -1 if it cannot find what you're looking for.
That being said, here's a better way to do what you're trying to do:
function getold_val(fieldName, str) {
var keyValuePairs = str.split("||");
var returnValue = null;
if(/||$/.match(str)) {
keyValuePairs = keyValuePairs.slice(0, keyValuePairs.length - 1);
}
var found = false;
var i = 0;
while(i < keyValuePairs.length && !found) {
var keyValuePair = keyValuePairs[i].split("::");
var key = keyValuePair[0];
var value = keyValuePair[1];
if(fieldName === key) {
returnValue = value;
found = true;
}
i++;
}
return returnValue;
}

Explain to me this snippet of JavaScript code

Can anyone explain this code snippet to me?
<script type="text/javascript">
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
document.write(koko);
document.write("<br>");
document.write(hu);
This is a function to extract variables from the document's query string, e.g. if the document's location is
example.com/test.htm?koko=123
querySt("koko") will return 123.
As a side note, the function should use local variables to prevent polluting the global name space:
var hu = window.location.search.substring(1);
var gy = hu.split("&");
...
for (var i = 0; i < gy.length; i++) {
The function is searching for a specified parameter in the query string an does return its value.
Imagine a url like this http://www.my.org/pg.htm?user=2&role=admin
function querySt(ji) {
// Gets all request parameters at client-side (QueryString)
// hu = ?user=2&role=admin
var hu = window.location.search.substring(1);
// Gets an array of substrings splitted by &
// gy[0] = user=2
// gy[1] = role=admin
var gy = hu.split("&");
// Iterate through the string array
for (i = 0; i < gy.length; i++) {
// Split into key/value pair
// ft[0] = 'user'
// ft[1] = '2'
ft = gy[i].split("=");
// See wether the key is 'koko'
if (ft[0] == ji) {
// return '2' if so
return ft[1];
}
}
}
var user= querySt("user");
document.write(user);
document.write("<br>");
document.write(hu);
This would print out 2 in this case. Hu would only printed out if defined outside the scope of the function querySt.
As far as I can see, the code gets the query string part of the URL
e.g: http://domain.com?querystparam1=somwthing&querystringparam2=somethingeles....
the query string part is ?querystparam1=somwthing&querystringparam2=somethingeles
hu contains everything but the question mark sign..
then an array en created from the rest split by the & sign, and then loop through the array and searching for koko and returns the value of the koko.

extract GET parameters from a user inputed url with javascript

I am looking to use javascript to extract the GET parameters from a user inputed url.
For example is a user enters a url say:
http://www.youtube.com/watch?v=ee925OTFBCA
I could get the v parameter
'ee925OTFBCA' as a variable
Thanks in Advance.
This should do the trick
// include this somewhere available
var Query = (function(){
var query = {}, pair, search = location.search.substring(1).split("&"), i = search.length;
while (i--) {
pair = search[i].split("=");
query[pair[0]] = decodeURIComponent(pair[1]);
}
return query;
})();
var v= Query["v"]
This only runs its computation once and creates an object with name/value pairs corresponding to those supplied as parameters
From here:
function getURLParam(strParamName){
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
return unescape(strReturn);
}
To use it:
var v = getURLParam('v')
You can use a function like this:
function querystring(key) {
var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
var r=[], m;
while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
return r;
}
Example:
var v = querystring('v')[0];
The function returns an array with all the values found in the query string. If you have a query string like ?x=0&v=1&v=2&v=3 the call querystring('v') returns an array with three items.
This is my simple snippet:
function extractParamValue(url, name) {
var pos = url.indexOf(name+'=')+name.length+1;
var value = url.substring(pos, url.indexOf('&', pos));
return value;
}

Javascript onclick get url value

I will like to get a url value upon onclick.
like this:
www.google.com/myfile.php?id=123
I want to get id and its value.
window.location.search will get you the ?id=123 part.
After reading the comments, it looks like you want a way to get the query string off a url, but not the current url.
function getParameters(url){
var query = url.substr(url.lastIndexOf('?'));
// If there was no parameters return an empty object
if(query.length <= 1)
return {};
// Strip the ?
query = query.substr(1);
// Split into indivitual parameters
var parts = query.split('&');
var parameters = {};
for(var i = 0; i < parts.length; i++) {
// Split key and value
var keyValue = parts[i].split('=');
parameters[keyValue[0]] = keyValue[1] || '';
}
return parameters;
}
function alertId(a){
var parameters = getParameters(a.href);
alert(parameters.id);
}
//onclick="alertId(this); return false;"

Categories

Resources