Concat/Edit/Manipulate Variables in Pre-request Script

Describe the bug
I’d like to combine several variables.
I have a series of requests that GET information and I’d like to combine several of them to be used in a POST. However, when I concat the variables or otherwise try to use it, the result is a string of the variable names, and not their values. ex. {{Var1}} {{Var2}} {{Var3}}

To Reproduce
Steps to reproduce the behavior:

  1. Collect several environment variables, these variables all work on their own and in different contexts. (Note: I’ve successfully used these variables separately, it’s combining them that is creating the problem)
  2. In Pre-request Script add the variables: Option 1) let string = “{{Var1}}” + “{{Var2}}” or Option 2) using concat (note must have “” around variable otherwise I receive an error about the {}'s matching.
  3. Check value of new string is updated correctly.
  4. Sadness.

Expected behavior
I’d like to be able to add variables so that if Var1= A, Var2 = B and Var3 = C in a Pre-request Script or Tests I could set Var4 to be {{Var1}}+{{Var2}}+{{Var3}} and get “ABC” and not {{Var1}}{{Var2}}{{Var3}}

App information (please complete the following information):

  • App Type [Native App]
  • Postman Version [e.g. 7.3.4]
  • OS: [Windows 10]

Thanks!

1 Like

You don’t use {{ }} in the Pre-request and Test scripts.

You have to use the pm object to retrieve and set variables

let a = pm.environment.get('A');
let b = pm.environment.get('B');
let c = pm.environment.get('C');

d = a + b +c; 

pm.environment.set('D',d);

https://learning.getpostman.com/docs/postman/scripts/postman_sandbox/

The Sandbox is also opensourced if you want to take a look at it.

2 Likes

HI @davidbeinhart,

You can access environment variables like so: {{Var1}} only on the Request path area and not in the test scripts. If you would like to access environment variables in a test script you would need to fetch the environment variable as so:
Var1 = pm.environment.get(“Var1”);

You can click on “Get an environment variable” code snippet on the right side of the Test scripts area to get the syntax right. After that, you can manipulate the data as you wish. Reference docs given here:https://learning.getpostman.com/docs/postman/environments_and_globals/variables_complete_reference/

1 Like

You could also do that like this but either way would work :slight_smile:

let concatString = `${pm.environment.get('A')} ${pm.environment.get('B')} ${pm.environment.get('C')}`

pm.environment.set('concatString', concatString);
4 Likes

+1 for template literals my favvvvv :heart_eyes:

Thank you all for the comments! This was very helpful.

1 Like

Thanks for this approach !!