In POSTMAN how do i get substring of response header item? - postman

I am using postman to get response header value like below:
var data = postman.getResponseHeader("Location") . //value is "http://aaa/bbb" for example
I can print the value via console.log(data) easily.
However, what I really want is "bbb". So I need some substring() type of function. And apparently 'data' is not a javascript string type, because data.substring(10) for example always return null.
Does anyone what i need to do in this case?
If any postman API doc existing that explains this?

You can set an environment variable in postman. try something like
var data = JSON.parse(postman.getResponseHeader("Location"));
postman.setEnvironmentVariable("dataObj", data.href.substring(10));

You have the full flexibility of JavaScript at your fingertips here, so just split the String and use the part after the last /:
var data = pm.response.headers.get("Location").split("/").pop());
See W3 school's documentation of split and pop if you need more in depth examples of JavaScript internals.

Some initial thought - I needed a specific part of the "Location" header like the OP, but I had to also get a specific value from that specific part.
My header would look something like this
https://example.com?code_challenge_method=S256&redirect_uri=https://localhost:8080&response_type=code&state=vi8qPxcvv7I&nonce=uq95j99qBCGgJvrHjGoFtJiBoo
And I need the "state" value to pass on to the next request as a variable
var location_header = pm.response.headers.get("Location");
var attributes = location_header.split('&');
console.log(attributes);
var len = attributes.length;
var state_attribute_value = ""
var j = 0;
for (var i = 0; i < len; i++) {
attribute_key = attributes[i].split('=')[0];
if (attribute_key == "state") {
state_attribute_value = attributes[i].split('=')[1];
}
j = j + 1;
}
console.log(state_attribute_value);
pm.environment.set("state", state_attribute_value);
Might you get the point here, "split" is the choice to give you some array of values.
If the text you are splitting is always giving the same array length it should be easy to catch the correct number

Related

Lookup and clear cell content google script

Sorry, I am new to scripting and this is probably a simple one to write; apologies!
I am trying to create a script that gets a range of order numbers in a column, then looks it up on another tab, and then clears a certain cell in that row.
I can get the script to look up the 1st ordernumber at the top of the list andd clear the cell I need clearing, but I cannot work out how to lookup and clear more than one order number at a time.
The logger returns all the values, so I think I need a loop, but I do not knwo where to start with that.
This is for a work project, but I have created a basic sample sheet to play around with:
https://docs.google.com/spreadsheets/d/19koKxFcOfWRz0mEaYs_lHQFgBrU19kDoeYaBY2WBe98/edit?usp=sharing
Can anyone help??
Thanks,
John
Here is the script so far:
function clearpostagecells(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Order Control');
var sheet2 = ss.getSheetByName('Order Database');
var find = sheet1.getRange(2,2,sheet1.getLastRow()-1).getDisplayValues();
Logger.log(find)
var values = sheet2.getRange(2, 1, sheet2.getLastRow()-1).getDisplayValues();
for (var i = 0; i < values.length; i++) {
var row = "";
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == find) {
row = i+2;
sheet2.getRange(row,7).clearContent();
}
}
}}

Generate Random String in Postman

I'm new at postman an im trying to generate a random string with letters(A-Z) and numbers(0-9). The string should have 20 points. I don't know how to set the Body and the pre req. I know that the Request must be POST. I have no idea how to start.
You can add scripts to the Pre-request Script to create this value.
This function will create the random value from the characters in the dataset and it will be 20 characters in length - The length can be adjusted when calling the function with your desired min and max values.
function randomString(minValue, maxValue, dataSet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
if (!minValue) {
minValue = 20;
maxValue = 20;
}
if (!maxValue) {
maxValue = minValue;
}
let length = _.random(minValue, maxValue),
randomString = "";
for (let i = 0; i < length; i++)
randomString += dataSet.charAt(Math.floor(Math.random() * dataSet.length));
return randomString;
}
pm.variables.set('randomString', randomString());
Adding a basic body like this is how you can use the randomly generated value:
{
"randomValue": "{{randomString}}"
}
When the request is sent, it will execute the function in the Pre-request Scripts tab and set the value as a local variable, this will then be used in the body of the request:
Per postman's docs you should be able to use {{$randomAlphaNumeric}} to generate a single character. $randomPassword seems to just generate 15 random alpha numeric characters so something like:
{{$randomPassword}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}
should give you 20 random characters without writing much code. This is a little terse, you could also just use the $randomAlphaNumberic selector 20 times.
Code for your Pre-request Script tab in Request:
function randomString(length=1) {
let randomString = "";
for (let i = 0; i < length; i++){
randomString += pm.variables.replaceIn("{{$randomAlphaNumeric}}");
}
return randomString;
}
STRING_LEN = 1000
pm.variables.set('randomString', randomString(STRING_LEN));
Just set the STRING_LEN to desired value.
Test it by using expression {{randomString}} i.e. in URL:
https://httpbin.org/anything?string={{randomString}}
Result:

Using where method with List<Map> Dart

I have a problem in flutter I want to do a search bar and I have a response to an api and I want to show data from server that contains a text from search bar my problem is where method doesn't work with List any ideas ?
Looking at your comment, there is no where method on String types. Instead of the for loop, you want something along these lines:
// Remove the for loop
// for(var i = 0; i <map.length; i++) { _results = jsonDecode(map[i]['address']).where((p)=>p.startsWith(query)).toList(); }
// Do this instead
_results = map.where((item) => item['address'].startsWith(query)).toList();
You should now be able to ditch the for loop.

Regular expression for finding the pound sign in the URL in Javascript?

I'd like to use location.pathname.match to find the number that comes after # in some.domain.com/#123 so that I can change some Javascript code from
res.render('index.ejs' ...
to
var pageNum = location.pathname.match(REGULAR_EXPRESSION_GOES_HERE)[1];
res.render('index' + pageNum + '.ejs' ...
So that way, I render index123.ejs instead of index.ejs.
I've been looking into regular expressions for how to do it and I'm a little lost. Any helpful souls out there have the magic answer?
[EDIT:] You've all been a huge help! I wish I wasn't too new to upvote you guys!
No need for all this manual stuff. THe location object has the data you want in the hash property. See: https://developer.mozilla.org/en-US/docs/DOM/window.location
So, just do:
var hash = window.location.hash;
if (hash.length && !isNaN(hash = parseInt(hash.substr(1)))) {
res.render('index' + hash + '.ejs');
}
else {
//oops, hash is not a number. Handle it.
}
var result = location.pathname.match(/some.domain.com\/\#(.*)$/);
alert(result [1]);
And don't forget to check if there is result [1]...
Your best bet would be
var pageNum = window.location.hash.replace(/\D+/g, '');
If you want to use regex, your code should look like this:
var pageNum = location.pathname.match(/#(\d+)/)[1];
Check this demo.

Fetch items from array using regex

I'm using action script and I have an array with more than 400.000 strings and now i'm using a loop and apply a regex to each item of the array to check if it's valid or not. In case it's valid, i put such item in a result array.
this process take too long, so it's a nuisance because all the process must executed many times.
I've been thinking about if there is any other way (faster) i could use for applying the regex to all items without using a loop.
Anyone could give me an idea?
EDIT
Here I attach the code used:
var list:Array;
var list_total:Array = new Array;
var pattern:String = '^['+some_letters+']{'+n+'}$';
var cleanRegExp:RegExp = new RegExp(pattern, 'gi');
for (var i:int=0; i<_words.length; i++) {
list = _words[i].match(cleanRegExp);
if (list != null)
for (var j:int=0; j < list.length; j++)
list_total.push(list[j]);
}
Thanks.
This is not a complete answer, but may help you optimize your code.
Try to do operations in your loop that are as efficient as possible. Time them using the global getTimer() function so you can compare which methods are the most efficient. When measuring/comparing, you may want to trigger your code many times, so that these differences are noticeable.
// before test
var startTime:Number = getTimer();
// do the expensive operation
var endTime:Number = getTimer();
trace("operation took ", endTime - startTime, " milliseconds.");
For example, one improvement is inside a for loop, is to not query the array for it's length each time:
for (var i:int = 0; i < myArray.length; i++)
Instead, store the length in a local variable outside of the array and use that:
var length:int = myArray.length;
for (var i:int = 0; i < length; i++)
The difference is subtle, but accessing the length from the local variable will be faster than getting it from the Array.
Another thing you can test is the regular expression itself. Try to come up with alternate expressions, or use alternate functions. I don't recall the specifics, but in one project we determined (in our case) that using the RegEx.test() method was the fastest way to do a comparison like this. It's likely that this may be as quick as String.match() -- but you won't know unless you measure these things.
Grant Skinner has some awesome resources available on his site. They are worth reading. This slide show/presentation on performance is worth looking at. Use the arrow keys to change slides.
Edit
Without hearing Grant's presentation, the initial slides may not seem that interesting. However, it does get very interesting (with concrete code examples) around slide #43: http://gskinner.com/talks/quick/#43
I do not think there is any good way to avoid using a loop.
The loop could be optimized further though.
Like someone already suggested read the array length to a var so the loop doesn't have to check length each iteration.
Instead of the nested loop use concat to join the list array to the lists_total. I'm not sure if this is actually faster. I guess it depends on how many matches the regexp gets.
Here is the modified code.
var list:Array;
var list_total:Array = new Array;
var pattern:String = '^['+some_letters+']{'+n+'}$';
var cleanRegExp:RegExp = new RegExp(pattern, 'gi');
var wordsLength:int = _words.length;
for (var i:int=0; i<wordsLength; i++) {
list = _words[i].match(cleanRegExp);
if (list != null)
lists_total = lists_total.concat(list);
}