I'm trying to recreate a simple javascript for loop to run in Zapier.
My Javascript skills would likely place me as "experienced but still newbish", so converting this to function correctly in Zapier has proven rather difficult. My code operates as expected until I attempt to rewrite it using Zapier's requirements.
For the example below, I have substituted the inputData with dummy text in "input".
Here's an example of my working model in JS:
const input = "Company Name: Shire Homes, Inc. | First Name: Frodo
| Last Name: Baggins |"
const fout = input.match(/\: (.*?) \|/g)
for (let i = 0; i < fout.length; i++) {
console.log(fout[i].slice(2, -2))
}
Which logs:
Shire Homes, Inc. Frodo Baggins
Since Zapier requires the data to be returned, instead of iterating over each string against the regex, I only get the first string and then it stops. How would one rewrite this to function correctly in Zapier?
I need to return each iteration as a string value since I'm going to be inserting the data elsewhere.
Thanks in advance!
Great question!
Instead of just iterating over the matches, you want to do something with each of them and get the result. The best way to do this is the .map
function (docs).
And like you mentioned, you need to return something from the whole function. There are a few options and which you want depends on what the eventual Zap will do.
"Shire Homes, Inc.,Frodo,Baggins"
) to use it all at once, then you'll want to join it. So let's look at the code!
// this is handled by Zapier already, but we need the variable to test it
const inputData = {text: "Company Name: Shire Homes, Inc. | First Name: Frodo | Last Name: Baggins |"}
const rawSegments = inputData.text.match(/\: (.*?) \|/g)
const segments = rawSegments.map(s => s.slice(2, -2))
// probably want to return an object
// option 1
// return {result: segments.join('')}
// option 2; probably don't want this
// return segments
// option 3; probably the best, but depends on the data being in the same order every time
return {
company: segments[0],
fname: segments[1],
lname: segments[2]
}
There's some JS shorthand in there, but hopefully it's clear what's going on.