how to extract substring from an environment variable - javascript

In postman response I have something similar to this
"References": [
"Ref/6789",
"Id/1234"
],
I want to set values 6789 and 1234 to different variables. I am using
let response = pm.response.json();
let bookref = response.References + '';
pm.environment.set("bookref", bookref);
// this sets bookref to Ref/6789,Id/1234
pm.environment.set("ref", bookref.split(',')[1]);
pm.environment.set("id", bookref.split(','));
Both the last 2 lines are failing with
ReferenceError: ref is not defined.
What is missing here? I have tried using .toString() function as well but it failed.

Try this one.
let ref = bookref[0].split('/')[1] ;
let id = bookref[1].split('/')[1] ;
pm.environment.set("ref", ref );
pm.environment.set("id", id );

Related

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

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 to update spreadsheet values from a variable?

I've created a function with three parameters (the client, the value I'm looking for in a table, the value new value to update), but until know I don't know how to update the cell with the determined value.
So far, I succeeded to look for the value in the table, but I cannot update the final cell with the value in parameter of the function. What is the way to do that?
async function modif(client, id1, id2)
{
const gsapi = google.sheets({version:'v4',auth: client });
for (i = 0; i < 50; i++)
{
const opt1 = {spreadsheetId: 'XXX', range: 'Sheet1!A' + (3+i)};
let data1 = await gsapi.spreadsheets.values.get(opt1);
if (parseInt(id1) === parseInt(data1.data.values))
{
const opt2 = {
spreadsheetId: 'xxx',
range: 'Sheet1!B' + (3+i),
valueInputOption: 'USER_ENTERED',
resource:{values : id2}
};
let res = await gsapi.spreadsheets.values.update(opt2);
console.log("modifications OK");
return;
}
}
}
I am supposed to have an updated cell, however instead I receive an error message saying : Invalid value at 'data.values'. Error is at the line resource:{values : id2}
Does anyone know how to solve this little error (I guess), I spent 2 hours on this error yesterday without being able to solve it :(
Thanks a lot in advance for your help,
I finally found out what was the problem... When I looked at the documentation here : https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values, I discovered the parameter "values" is an array of arrays...
As a result I only had to change my syntax to goes from : resource:{values : id2} to : resource:{values : [[id2]]}
Cheers,

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 to concat buffers with delimiter in node.js?

I'm trying to concat two buffers with a space in between them in Node.js.
Here is my code.
var buff1 = new Buffer("Jumping");
var buff2 = new Buffer("Japang");
var buffSpace = new Buffer(1);
buffSpace[0] = "32";
var newBuff = Buffer.concat([buff1, buffSpace, buff2], (buff1.length + buff2.length + buffSpace.length));
console.log(newBuff.toString());
As per official doc, the first argument will be the Array list of Buffer objects. Hence I've created buffSpace for space.
Class Method: Buffer.concat(list[, totalLength])
list : Array List of Buffer objects to concat
totalLength: Number Total length of the buffers when concatenated
I'm getting the result as expected but not sure whether it is right way to do so. Please suggest if any better solution to achieve the same.
There are three changes I would suggest.
First, if you are using Node v6, use Buffer.from() instead of new Buffer(), as the latter is deprecated.
Second, you don't need to pass an argument for totalLength to Buffer.concat(), since it will be calculated automatically from the length of all of the buffers passed. While the docs note it will be faster to pass a total length, this will really only be true if you pass a constant value. What you are doing above is computing the length and then passing that, which is what the concat() function will do internally anyway.
Finally, I would recommend putting this in a function that works like Array.prototype.join(), but for buffers.
function joinBuffers(buffers, delimiter = ' ') {
let d = Buffer.from(delimiter);
return buffers.reduce((prev, b) => Buffer.concat([prev, d, b]));
}
And you can use it like this:
let buf1 = Buffer.from('Foo');
let buf2 = Buffer.from('Bar');
let buf3 = Buffer.from('Baz');
let joined = joinBuffers([buf1, buf2, buf3]);
console.log(joined.toString()); // Foo Bar Baz
Or set a custom delimiter like this:
let joined2 = joinBuffers([buf1, buf2, buf3], ' and ');
console.log(joined2.toString()); // Foo and Bar and Baz
Read the Buffer stream and save it to file as:
const data = [];
req.on('data', stream => {
data.push(stream);
});
req.on('close', () => {
const parsedData = Buffer.concat(data).toString('utf8');
fs.writeFileSync('./test.text', parsedData);
});

Categories

Resources