Javascript onclick get url value - javascript

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

Related

Get Parameter from URL and use it in dictionary

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.

Build key/value Object from slash-separated URL

Given a slash separated URL like http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3 how could I build a key/value Object with the dynamic parameters (param1/value, param2/value2...) of this URL?
Valid parameters always have this slash separated paramand value format and some/fixed/path would be a substring manually provided.
I tried to split the full URL (or whatever it could be) by the fixed substring and I managed to slice the dynamic params out of it as I wanted but I couldn't create the key/value Object as I needed:
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
url.split( uri ).forEach(function(x){
var arr = x.split('/');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log( result );
But this piece of code only brings me the first pair instead of all of them and it requires the uri to obligatorily have a trailing slash. If the substring doesn't have it or has one to the left it acts all weird with a blank key and the first key as value o.O
I know it's simple, but I just can't do it. I tried to search but this must have a very specific way to refer to because I couldn't find by my own.
One last thing, if you don't mind explain instead of just give me the fish, I'd appreciate, so there won't have a next time... hopefully
You were only taking the second part after some/fixed/path/. You need to split this second part and iterates over the array. On each even index, I create a new property in the object with the name of the previous element
x is the current element
i is the current index
a is the array containing each element after splitting with /
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
var paramsToSplit = url.split(uri)[1];
paramsToSplit.split('/').forEach((x,i,a)=>{
if(i%2)
result[a[i-1]] = x;
});
console.log( result );
Try this:
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var url = url.substring(url.indexOf(uri) + uri.length)
var options = url.split('/');
var results = [];
for(var i=0;i<options.length; i+=2){
results.push({[options[i]]:options[i+1]})
}
Are you looking for somethig like that?
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var params = [];
var values = [];
var results = {};
url.split( uri )[1].split('/').forEach(function(e,i) {
if(i%2==0){
params.push(e)
} else {
values.push(e);
}
})
console.log( params, values );
params.forEach(function(e,i) {
results[e] = values[i];
});
console.log( results );
You may do as follows;
var text = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
result = text.split("/")
.slice(6)
.reduce((r,c,i,a) => i&1 ? Object.assign(r,{[a[i-1]]: c}) : r, {});
console.log(result);
You are quite close, you basically need to make another for loop for your produced arr and step every 2 values. Like so...
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
url.split( uri ).forEach(function(x){
var arr = x.split('/');
var step;
for (step = 0; step <= arr.length; step += 2) {
arr[step + 1] && (result[arr[step]] = arr[step + 1]);
}
});
console.log( result );

Splitting string on first equals sign in javascript

I am trying to use Javascript to split some data out of a url The url looks along the lines of....
var1=green&var2=yellow&newUrl=[url.php?id=2]
I am managing to split the url by the '&' signs to give me one array of three items. I am then trying to split this array by the first '=' sign to give me a list of fields and variables. Its working fine until it hits the second = sign within the newUrl field. Any ideas of how I can split this string at the first '=' sign.
my code so far is...
var href = $(this).attr("href");
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
var str = vars[i].split("=");
alert(str[0] +':' +str[1]);
}
}
my results are
var1:green var2:yellow var3:[url.php?id
Any ideas?
**Edit to show my final code based on Wand Maker's solution **
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
alert(str[0] +':' +str[1].substring(1);
}
Try something like below for splitting around =
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
You could use join() for the third element in the array as below:
var lst = href.split("&");
var var1 = href[0].split("=")[1];
var var2 = href[1].split("=")[1];
var var3 = href[2].split("=").slice(1,2).join("");
function splitFirstInstance(str,item){
var res = [];
var found = true;
res.push("");
for (var i = 0; i < str.length;i++){
if (str[i] === item && found === true){
res.push("");
found = false;
} else {
res[res.length-1] += str[i];
}
}
return res;
}
splitstr("I Want to Split First a","a"); // ["I W","nt to Split First a"]

Append number to a comma separated list

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?
Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.
If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}
You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

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

Categories

Resources