Sometimes one needs to compose multiple strings into one string inside a calculation field or a workflow automation. This guide shows how to do that in JavaScript in an easy and maintainable way.
The easiest way leveraging modern ES2021 JavaScript syntax is to use template literals. They allow dynamic and readable string composition.
Consider the following example:
- We have a form url that we would like to add query parameters to, in order to prefill values
- The values to prefill are available as existing variables, or as field tokens in a calc field. For simplicity it is
first_name
andlast_name
in this example.
We start by declaring the base form URL:
const base_form_url = `https://aweseomeformprovider.com/form/123456`
We will now create a string that holds the query params:
const queryParams = [ { key: 'first_name', value: first_name }, { key: 'last_name', value: last_name } ];
// this will create a string in the form of `first_name=xy&last_name=z`
const query_params_str = queryParams.map(param => `${param.key}=${param.value}`).join('&');
// yield the final URL https://aweseomeformprovider.com/form/123456?a=b...&...
const finalUrl = `${base_form_url}?${query_params_str}`;
More examples will be added here on the fly. Feel free to also add your ideas in the comments!
Some other great related examples by community members: