I want to fetch loginID and password from below code - javascript

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

Related

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

How can I get the last object in this JSON array?

I'm trying to use player data from a football stats API, but I can't seem to get data for the current season (which can be found in the last object in the array). For some reason I'm only getting data for the third index (code below).
.then(data => {
//BIO
const bio = data['data'][0]
const nameValue = bio['fullname']
const imageValue = bio['image_path']
const teamValue = bio['team']['data']['name']
const countryValue = bio['nationality']
const birthdateValue = bio['birthdate']
const heightValue = bio['height']
const positionValue = bio['position']['data']['name']
//STATS
const stats = bio['stats']['data']['data'.length - 1]
const appearancesValue = stats['appearences']
Here is an image of the JSON data I am trying to access. In this instance I should be getting data from [4] but I'm getting it from [3].
I'm quite inexperienced so I feel like I must be making a silly mistake somewhere! Appreciate any help.
the 'data'.length in the bio['stats']['data']['data'.length - 1] part will evaluate to the length of the "data" string. so it is always 4.
You most likely wanted the length of the array so it should be
bio['stats']['data'][bio['stats']['data'].length - 1]
Or you could extract it beforehand in a variable, for clarity
const dataLength = bio['stats']['data'].length;
const stats = bio['stats']['data'][dataLength - 1];
Also since you are using literals for the object properties you do not need to use the [] notation.
const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];
and you can do that with the rest of the code as well, to avoid typing all the ['..']
Building up on Henry Walker's answer.
Using the new JavaScript Array.at() method allows you to enter both positive and negative indices.
This code:
const dataLength = bio.stats.data.length;
const stats = bio.stats.data[dataLength - 1];
Would simply translate to:
const stats = bio.stats.data.at(-1);
Giving you the last element in the array.
As data object signifies, it has 5 objects in it, you can this particular object at 3rd place as in an array 1st value is stored at index 0. Try using this code to fetch the last object
var lastObject = bio.stats.data[bio.stats.data.length-1].player_id

How to get a param from the url?

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

How do I change \" back to " in javascript?

I'm a beginner to Node.js and MySQL so bear with me. The code below is in my routes for my localhost server and the database when saved at first is fine, but when I try to retrieve it and push it back into my database by storing the old one in a new array, it changes the "" to \"\". What I want is for it to be still "".
I've tried looking around the web for ways to change the formatted string quotes from \"\" back to "" but to no avail and I also tried formatting the score from string back to a number but I realized that even if I did that, it would still end up being a string when stored in the database and when I retrieve it, it would be the same.
let { score } = req.body;
let { date } = req.body;
score = Number(score);
var score_date = [score, date];
wMissing.findOne({
raw : true
}).then((missing) => {
var sessionID = missing.testSessionID;
registerPatient.findOne({
where: {
nric : sessionID
},
raw : true
}).then((patient) => {
var height = patient.height;
height = height / 100
var weight = patient.weight;
var bmiVar = (weight / (height * height)).toFixed(2);
// *This is where my problem starts*
if (missing.wMissingScore == null){
var newArray = score_date;
} else {
var newArray = [missing.wMissingScore];
newArray.push(score_date);
}
newArray = JSON.stringify(newArray);
wMissing.update({
bmi: bmiVar,
wMissingScore: newArray,
name: patient.fullname,
nric: sessionID,
datePlayed: date
}, {
where: {
nric: sessionID
}
}).then(() => {
res.redirect('workoutDiets');
}).catch(err => console.log(err));
The expected output is supposed to be [["2","24/7/2019"],["3","24/7/2019"]]
But instead I'm getting ["[\"2\",\"24/7/2019\"]",["3","24/7/2019"]]
I'm still unaware of any method to change back the \"\" to "" instead. can anyone please help me to improve on my code?
Actually, what's happening is that the first element of the array is being stored as a string, if you watch carefully, the second element is written correctly as an array of strings.
The problem is the first element, you're having a special case.
If i understand correctly ´´´missing.wMissingScore´´´ is a pure string
What you can do is:
´´´
if (missing.wMissingScore == null){
var newArray = score_date;
} else {
var formatedMissingScore= missing.wMissingScore.replace("\"", "").replace("[", "").replace("]", "").split(",");
var newArray = [formatedMissingScore];
newArray.push(score_date);
}
´´´
That way you're formatting your first element string so its not text anymore and should match what you are trying to get.
#charlietfl mentioned about JSON.parse() and it worked! I just changed my else statement to
var newArray = [JSON.parse(missing.wMissingScore)];
and it managed to save the score back to what it originally was.

Writing a query parser in javascript

I'm trying to write a parser that supports the following type of query clauses
from: A person
at: a specific company
location: The person's location
So a sample query would be like -
from:Alpha at:Procter And Gamble location:US
How do i write this generic parser in javascript. Also, I was considering including AND operators inside queries like
from:Alpha AND at:Procter And Gamble AND location:US
However, this would conflict with the criteria value in any of the fields (Procter And Gamble)
Use a character like ";" instead of AND and then call theses functions:
var query = 'from:Alpha;at:Procter And Gamble;location:US';
var result = query.split(';').map(v => v.split(':'));
console.log(result);
And then you'll have an array of pairs, which array[0] = prop name and array[1] = prop value
var query = 'from:Alpha;at:Procter And Gamble;location:US';
var result = query.split(';').map(v => v.split(':'));
console.log(result);
Asuming your query will always look like this from: at: location:
You can do this:
const regex = /from:\s*(.*?)\s*at:\s*(.*?)\s*location:\s*(.*)\s*/
const queryToObj = query => {
const [,from,at,location] = regex.exec(query)
return {from,at,location}
}
console.log(queryToObj("from:Alpha at Betaat: Procter And Gamble location: US"))
However, adding a terminator allow you to mix order and lowering some keywords:
const regex = /(\w+):\s*(.*?)\s*;/g
const queryToObj = query => {
const obj = {}
let temp
while(temp = regex.exec(query)){
let [,key,value] = temp
obj[key] = value
}
return obj
}
console.log(queryToObj("from:Alpha at Beta;at:Procter And Gamble;location:US;"))
console.log(queryToObj("at:Procter And Gamble;location:US;from:Alpha at Beta;"))
console.log(queryToObj("from:Alpha at Beta;"))

Categories

Resources