Albato
  • Language
    En
    English
    Portuguese
    Spanish
  • Welcome to Albato Help

    How to use JavaScript code in Albato


    IN THIS ARTICLE

    JavaScript Code tool allows you to execute custom JavaScript directly inside your Automation. It’s designed for cases where standard tools are not enough, for example, when you need to perform calculations, transform data, split values, or generate custom outputs before passing them to the next steps.

    This tool gives you flexibility to work with data inside an Automation using JavaScript logic you define yourself.

     

    How the tool works

    1. To add the JavaScript Code tool to your Automation, click the “+” button in your interface. Then, select Code.

    jscodenew1.png

    1. Click Select to choose the JavaScript Code.

    jscodenew2.png

    1. First, you need to configure Input Data. This means you create variables, name them, and define which values to assign to each one. These variables can then be used in your code, along with any new variables you define inside the script.

    jscodenew3.png

    For each variable, you need to:

    • define a name;
    • select a value from the previous steps.
     
    1. To add more variables, click Add field. This will create a new row where you can specify the variable name and configure its value. You can delete unnecessary variables (fields) if needed.

    jscodenew4.png

    1. Then, configure Output Data. Here, you manually specify the name and type of any variables you want to get as output. In the following steps of your Automation, you’ll be able to use the fields you've defined in this section.

    jscodenew5.png

    Configuring Output Data is mandatory, even if you didn’t create any new variables in the code.

    1. After that, write your JavaScript code using the variables you've declared or create new ones based on them.

    Albato cannot guarantee the performance of your custom code and does not provide support for it. Please use this tool only if you feel confident working with JavaScript.

    1. In the following steps, you’ll see the same fields you configured in the Output Data section and will be able to use them throughout your Automation.

    2. If, for any reason, the code fails to execute, this step in the automation will be considered an error. The execution log will display the error message returned by the JavaScript engine.

     

    Limitations and safety

    • JavaScript execution runs in an isolated environment
    • External network requests are not allowed
    • The fetch function is disabled
    • Execution errors stop the Automation step
     

    Examples of Run JavaScript Code

    Case 1. Subtracting Start DateTime from End DateTime and returning the result in minutes

    This use case is helpful when you need to calculate the duration of an event, such as order processing time or call length.

    • Input: dateStart, dateEnd
    • Output: diffMinutes (Number)
     
    dateStart = new Date(dateStart);
    dateEnd = new Date(dateEnd);
    let difMinutes = (dateEnd – dateStart) / (1000 * 60);
      

    case1.png

     

    Case 2. Splitting DateTime into separate Date and Time values and trimming seconds

    Use this example when a service returns a single DateTime value, but the next step requires date and time as separate fields.

    • Input: dateTime (Unix timestamp)
    • Output: date (String), time (String)
     
    dateTime = new Date(+dateTime);
    function dateEdit(arr) {
    return arr.map((el) => {
    return el < 10 ? “0” + el : el;
    });
    }
    let date = dateEdit([
    dateTime.getDate(),
    dateTime.getMonth() + 1,
    dateTime.getFullYear(),
    ]).join(“.”);
    let test = dateEdit([dateTime.getHours(), dateTime.getMinutes()]).join(“:”);
      

    case2.png

     

    Case 3. Splitting a string into multiple values

    This use case is helpful when one field contains several values separated by a delimiter.

    • Input: value
    • Output: first (String), second (String)
     
    const parts = value.trim().split(/\s+|,|\|/);
    const first = parts[0];
    const second = parts?.[1];
      

    Splitting multiple values using a space as a delimiter

    num4 = num4.trim().split(‘ ‘);
    let name = num4[0];
    let familyname = num4?.[1];
    let surname = num4?.[2];
      

    Splitting values using a comma as a delimiter

    A = A.trim().split(“\,”);
    let num1 = A[0];
    let num2 = A?.[1];
      

    Splitting values using the “|” delimiter

    UF_CRM_1669820909984 = UF_CRM_1669820909984.trim().split(“\|”);
    let name = UF_CRM_1669820909984[0];
    let surname = UF_CRM_1669820909984?.[1];
      

    Splitting a full name into first and last name

    Use this example when a service returns a full name as a single string and you need to split it into separate fields (for example, first name and last name) before passing the data to the next steps of your Automation.

    Input: fullName (String)
    Output: name (String), lastname (String)

    let [firstName, lastName] = fullName.trim().split(" ");
    

    let name = firstName; let lastname = lastName;

    case3.png

     

    Case 4. Parsing query parameters from a URL

    Use this example to extract parameters from a URL query string.

    Input: refererurl
    Output: parsedGet (String)

     
    function parseQueryParams(url) {
    const queryString = url.split(“?”)[1];
    if (!queryString) {
    return {};
    }
    const queryParams = {};
    const pairs = queryString.split(“&”);
    for (let i = 0; i < pairs.length; i++) {
    const pair = pairs[i].split(“=”);
    const key = decodeURIComponent(pair[0]);
    const value = decodeURIComponent(pair[1] || “”);
    if (queryParams.hasOwnProperty(key)) {
    if (Array.isArray(queryParams[key])) {
    queryParams[key].push(value);
    } else {
    queryParams[key] = [queryParams[key], value];
    }
    } else {
    queryParams[key] = value;
    }
    }
    return queryParams;
    }
    const parsedGet = parseQueryParams(url);
      

    Replace the input value with url in the last line of the code. Set parsedGet as the output value with the StringArray type.

    You can modify the example and add:

    let one = parsedGet[0]; let two = parsedGet[1];

    You can also use these values as output variables with the String type.

     

    Case 5. Cleaning HTML tags from text

    This example is useful when email or message content arrives in HTML format and needs to be cleaned before further processing.

    • Input: html
    • Output: html (String)
     
    let regexp = /<(\/?[^>]+)>|(\n)|(\s{4,})/gm;
    html = html.replace(regexp, ”).trim();
      

    Case 6. Converting date and time to Unix timestamp

    Use this example when an external system requires Unix time instead of a formatted date.

    Input: amo_datetime (YYYY-MM-DD HH:MM:SS)
    Output: unixTime (Number)

     
    let [date, time] = amo_datetime.split(” “);
    let [year, month, day] = date.split(“-“).map(Number);
    let [hours, minutes, seconds] = time.split(“:”).map(Number);
    let ls_deadline_unix = new Date(year, month – 1, day, hours, minutes, seconds).getTime();
      
     
     

    Case 7. Returning different values depending on the day of the week

    This example can be used to build Automations with day-specific logic. Use this example when your Automation needs to send different messages depending on the current day of the week.

    For example, you can configure the logic so that one message is sent on Monday, another on Tuesday, a different one on Wednesday, and so on.

    const messages = {
      0: "Sunday message",
      1: "Monday message",
      2: "Tuesday message",
      3: "Wednesday message",
      4: "Thursday message",
      5: "Friday message",
      6: "Saturday message"
    };
    

    const result = messages[new Date().getDay()];

     

    Case 8. Capitalizing the first letter of each word

    Use this example to format names or text values before sending them to another app.

    Input: str Output: formatted (String)

    function toCapitalLetter(str) {
      if (!str) return str;
      return str.trim().toLowerCase().split(" ").map(w => w[0].toUpperCase() + w.slice(1)).join(" ");
    }
    const formatted = toCapitalLetter(str);
      
     

    Case 9. Parsing multiple metrics from a single text string

    Use this example when a service returns several metrics in one text field and you need to extract them into separate output variables (for example, date, steps, kcal, prot, and others) to use them in the next steps of your Automation.

    javascriptcase10.png

    • Input: input (String)
    • Output: date (String), pasos (String), kcal (String), prot (String), gr (String), carb (String), gym (String), spa (String), sup (String), obs (String)
    function parseMetrics(str) {
    const result = {};
    const dateMatch = str.match(/^\d{2}\/\d{2}\/\d{4}/);
    if (dateMatch) {
    result.date = dateMatch[0];
    }
    const rest = str.replace(result.date, '').trim();
    const regex = /(\w+):\s([^:]+?)(?=\s\w+:|$)/g;
    let match;
    while ((match = regex.exec(rest)) !== null) {
    const key = match[1];
    const value = match[2].trim();
    result[key] = value;
    }
    return result;
    }
    

    const parsed = parseMetrics(input); const date = parsed.date; const pasos = parsed.pasos; const kcal = parsed.kcal; const prot = parsed.prot; const gr = parsed.gr; const carb = parsed.carb; const gym = parsed.gym; const spa = parsed.spa; const sup = parsed.sup; const obs = parsed.obs;

     

    The result of the tool, which can be used in the next steps of your Automation.

    javascriptcase10-1.png

    You can now use the Run JavaScript Code tool for calculations, data transformation, formatting, and conditional logic inside your Automations.

    Did this answer your question?