问题
I will have a variety of URLs that all contain the same Query Parameter:
https://www.example.com/landing-page/?aid=1234
I would like to extract the "1234" by searching for the "aid" query parameter in the URL.
The javascript will run in Zapier:
Example javascript block in Zapier
Zapier notes: What input data should we provide to your code (as strings) via an object set to a variable named inputData?
I don't have much experience with javascript or coding in general, but the end result would be the 4-digit "aid" value that I would then reference when posting via webhook to an API.
edit: I checked the similar answers and appreciate the links however I am not sure how to utilize "inputData" and "url" in Zapier with the provided answers.
回答1:
David here, from the Zapier Platform team.
While the comments above point you towards regex, I recommend a more native approach: actually parsing the url. Node.js has a great standard library for doing that:
// the following line is set up in the zapier UI; uncomment if you want to test locally
// const inputData = {url: 'https://www.example.com/landing-page/?aid=1234'}
const url = require('url')
const querystring = require('querystring')
const urlObj = url.parse(inputData.url) /*
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.example.com',
port: null,
hostname: 'www.example.com',
hash: null,
search: '?aid=1234',
query: 'aid=1234',
pathname: '/landing-page/',
path: '/landing-page/?aid=1234',
href: 'https://www.example.com/landing-page/?aid=1234' }
*/
const qsObj = querystring.parse(urlObj.query) // { aid: '1234' }
return { aid: qsObj.aid }
Depending on how confident you are that the data you're looking for will always be there, you may have to do some fallbacks here, but this will very reliably find the param(s) you're looking for. You could also follow this code step with a Filter
to ensure latter steps that depend on the aid
don't run if it's missing.
Let me know if you've got any other questions!
来源:https://stackoverflow.com/questions/51640884/how-do-i-parse-a-url-for-a-specific-query-paramter-in-javascript