How to get a param from the url? - javascript

I have a url like this:
http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262
I need to get the param called "codice" from the url of this page and use it in a query. I tried with this code:
render() {
const params = new URLSearchParams(this.props.location.search);
const codiceHash = params.get('codice');
console.log(params.get('codice'))
return (
<div className={styles}>
<div className="notification">
<h2>Prima Registrazione eseguita con successo</h2>
</div>
{this.saveEsegue(email, transactionHash , blockHash, now, "FR", codiceHash)}
</div>
)
}
But what I get back from the console.log is null.
What am i doing wrong?

Your URL is invalid. You cannot have # and then later two ? in it.
Your ?codice shoould be &codice
Here is one way to get at codice
const invalidHref = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262&somethingelse"
const codice = invalidHref.split("codice=")[1].split("&")[0];
console.log(codice)
Here is how it would have worked on a valid URL
const params = new URLSearchParams("http://localhost:3000/#/firstregistration?panel=4&codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262")
const codice = params.get("codice")
console.log(codice)

The parameters string isn't correct in the URL, but to get the string from what you've provided I'd use RegEx.
This way it doesn't matter where the codice parameter is in the URL (ie you can add more parameters without breaking it. RegEx will just pick it out.)
const url = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; // window.location.href;
const codice = url.match(/(codice=)([a-zA-Z0-9]*)/)[2];
console.log(codice) // prints fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

I suggest you to use the module querystring to achieve that, this is one of the top used for this purpose.
Example:
console.log(this.props.location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

Since you only want the one parameter and you know which values it can hold I would use regex.
var r = /codice=([a-z0-9]+)&/g
var matches = r.exec('http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262')
console.log(matches[1])
>> fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262

The code snippet will return
codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262
change url_string to window.location.href to grab the current URL of the page
var url_string = "http://localhost:3000/#/firstregistration?panel=4?codice=fea023b0cb134b845d49a789a9149ab4321574fe093a5fceac1083959e26d262"; //window.location.href
var b = url_string.substring(url_string.indexOf("?codice=") + 1);
console.log(b);

Related

I need to allocate a url to very student name in Javascript

The name list is supposedly as below:
Rose : 35621548
Jack : 32658495
Lita : 63259547
Seth : 27956431
Cathy: 75821456
Given you have a variable as StudentCode that contains the list above (I think const will do! Like:
const StudentCode = {
[Jack]: [32658495],
[Rose]: [35621548],
[Lita]: [63259547],
[Seth]: [27956431],
[Cathy]:[75821456],
};
)
So here are the questions:
1st: Ho can I define them in URL below:
https://www.mylist.com/student=?StudentCode
So the link for example for Jack will be:
https://www.mylist.com/student=?32658495
The URL is imaginary. Don't click on it please.
2nd: By the way the overall list is above 800 people and I'm planning to save an external .js file to be called within the current code. So tell me about that too. Thanks a million
Given
const StudentCode = {
"Jack": "32658495",
"Rose": "35621548",
"Lita": "63259547",
"Seth": "27956431",
"Cathy": "75821456",
};
You can construct urls like:
const urls = Object.values(StudentCode).map((c) => `https://www.mylist.com?student=${c}`)
// urls: ['https://www.mylist.com?student=32658495', 'https://www.mylist.com?student=35621548', 'https://www.mylist.com?student=63259547', 'https://www.mylist.com?student=27956431', 'https://www.mylist.com?student=75821456']
To get the url for a specific student simply do:
const url = `https://www.mylist.com?student=${StudentCode["Jack"]}`
// url: 'https://www.mylist.com?student=32658495'
Not sure I understand your second question - 800 is a rather low number so will not be any performance issues with it if that is what you are asking?
The properties of the object (after the trailing comma is removed) can be looped through using a for-in loop, (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
This gives references to each key of the array and the value held in that key can be referenced using objectName[key], Thus you will loop through your object using something like:
for (key in StudentCode) {
keyString = key; // e.g = "Jack"
keyValue = StudentCode[key]; // e.g. = 32658495
// build the urls and links
}
to build the urls, string template literals will simplify the process (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) allowing you to substitute values in your string. e.g.:
url = `https://www.mylist.com/student=?${StudentCode[key]`}
Note the use of back ticks and ${} for the substitutions.
Lastly, to build active links, create an element and sets its innerHTML property to markup built using further string template literals:
let link = `<a href=${url}>${keyValue}</a>`
These steps are combined in the working snippet here:
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const studentLinks = [];
for (key in StudentCode) {
let url = `https://www.mylist.com/student=?${StudentCode[key]}`;
console.log(url);
studentLinks.push(`<a href href="url">${key}</a>`)
}
let output= document.createElement('div');
output.innerHTML = studentLinks.join("<br>");
document.body.appendChild(output);

Capture and Remove URL segment in custom JS - GTM

I need a custom JS variable for GTM that excludes everything from "/p/" until the end or the next "/", what happens first.
The url after the /p/ can be anything, any length, and have nothing afterwards.
Before:
hostname/category/brand/some-snicker-model/p/NIBQ5448001
hostname/campaign/some-snicker-model/p/AB434222/?device=type
After:
hostname/category/brand/some-snicker-model
hostname/campaign/some-snicker-model/?device=type
Something like that should works:
/\/p\/.*?(?=(\/|\?|$))/g
const data = ["hostname/category/brand/some-snicker-model/p/NIBQ5448001", "hostname/campaign/some-snicker-model/p/AB434222/?device=type"]
const regex = /\/p\/.*?(?=(\/|\?|$))/g;
data.forEach(url => {
console.log(url.replace(regex, ''))
})
// hostname/category/brand/some-snicker-model
// hostname/campaign/some-snicker-model/?device=type
Another better alternative would be to use URL(), as it allows to separate the url according to the origin, the path name, the search value, etc.
let data = [
'https://www.hostname.com/category/brand/some-snicker-model/p/NIBQ5448001',
'https://www.hostname.com/campaign/some-snicker-model/p/AB434222/?device=type',
'https://www.hostname.com/category/brand/some-snicker-model/p/NIBQ5448001?device=mobile'
];
let pattern = /\/p\/.*?(?=(\/|$))/g;
data.forEach(element => {
let url = new URL(element);
let new_url = url.origin + url.pathname.replace(pattern, '') + url.search
console.log(new_url)
});

I want to fetch loginID and password from below code

const fs = require('fs');
// var fileRefer=new Array();
var fileRefer = fs.readFileSync('D:\\NgageAuto\\LoginID\\Creds.txt').toString().split("\n");
for(i in fileRefer) {
console.log(fileRefer[i]);
}
Ouput:- Date: 2021-11-08 16:56:42 LoginID: pvgA1245 Password: Root#123
it's one of the example which is in file i want LoginID value i.e "pvgA1245 and password value i.e Root#123
Please , help me how can i make it!!!
there are hundreds of solutions to this problem, some having advantages in different scenarios then others.
Here are some for using split() or using a regex match. Each either using destructuring or just "normally assign" the variables. Regex has the advantage, that it can be used more flexible for example if sometimes the line schema is different and Password is missing. But if you can be sure that the schema is always the same or just wanna skip lines that don't have all values, split() is totally fine.
You would just add the relevant code snippet inside your for loop
let i = "Date: 2021-11-08 16:56:42 LoginID: pvgA1245 Password: Root#123";
// split and destructure
const [ , , , , id, ,pw,] = i.split(" ");
console.log(id, pw);
// split and normally assign
const a = i.split(" ");
const id2 = a[4];
const pw2 = a[6];
console.log(id2, pw2);
// regex and destructure
const [, id3, pw3] = i.match(/(?:LoginID: ([^\s]*)) ?(?:Password: ([^\s]*))/);
console.log(id3, pw3);
// regex and normally assign
const m = i.match(/(?:LoginID: ([^\s]*)) ?(?:Password: ([^\s]*))/);
const id4 = m[1];
const pw4 = m[2];
console.log(id4, pw4);

Getting data in console but shows undefined in main output

I'm working on a app with electron using axios to get api data, but when i use to display data it shows undefined in screen and when i output it, it shows the correct value!! Some help would be appreciated!
const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const axios = require('axios');
const notifyBtn = document.querySelector('.notify-btn');
const price = document.querySelector('.price');
const targetPrice = document.querySelector('.target-price');
function getBTC(){
axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&api_key={api_key}')
.then(function(response) {
let cryptos = response.data;
price.innerHTML = '$'+cryptos;
console.log(response.data);
});
}
getBTC();
setInterval(getBTC, 30000);
I get a output in console:
Object: USD: 3560.263(Current price of bitcoin)
I get output on main screen:
'undefined'
I think its because it an object so how can i display an object?
I may be wrong!!
ThankYou!!
It's not
price.innerHTML = '$'.cryptos;
// but
price.innerHTML = '$' + cryptos.USD;
Add .USD because cryptos is an object. And the value is saved into the key USD
You are accessing the property of a string.
price.innerHTML = '$'.cryptos;
^^^ property
I think you wanted to concat values with a + operator
price.innerHTML = '$' + cryptos;
try using
price.innerHTML = '$'+cryptos.USD;
What are you trying to achieve with '$'.cryptos; ?
If you are trying to concatenate some strings this is not how it works!
try "$"+cryptos
You should use only primitive type variables when composing a string.
If you want to show an object, you could simply use JSON.stringify(cryptos) to obtain the JSON string of the whole object.
Otherwise, you could print any other object property that is a primitive type, like cryptos.USD.

How can I use underscore in name of dynamic object variable

Website that I'm making is in two different languages each data is saved in mongodb with prefix _nl or _en
With a url I need to be able to set up language like that:
http://localhost/en/This-Is-English-Head/This-Is-English-Sub
My code look like that:
var headPage = req.params.headPage;
var subPage = req.params.subPage;
var slug = 'name';
var slugSub = 'subPages.slug_en';
var myObject = {};
myObject[slugSub] = subPage;
myObject[slug] = headPage;
console.log(myObject);
Site.find(myObject,
function (err, pages) {
var Pages = {};
pages.forEach(function (page) {
Pages[page._id] = page;
});
console.log(Pages);
});
After console.log it I get following:
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Is you can see objectname subPages.slug_en is seen as a String insteed of object name..
I know that javascript does not support underscores(I guess?) but I'm still looking for a fix, otherwise i'll be forced to change all underscores in my db to different character...
Edit:
The final result of console.log need to be:
{ subPages.slug_en: 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Insteed of :
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Otherwise it does not work
The reason you are seeing 'subPages.slug_en' (with string quotes) is because of the . in the object key, not the underscore.
Underscores are definitely supported in object keys without quoting.
Using subPages.slug_en (without string quotes) would require you to have an object as follows:
{ subPages: {slug_en: 'This-Is-English-Sub'},
name: 'This-Is-English-Head' }
Which you could set with the following:
myObject['subPages']['slug_en'] = subPage;
Or simply:
myObject.subPages.slug_en = subPage;

Categories

Resources