How do I parse a URL for a specific Query Paramter in javascript?

こ雲淡風輕ζ 提交于 2021-02-05 09:42:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!