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

后端 未结 1 1080
暗喜
暗喜 2021-01-27 06:49

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

相关标签:
1条回答
  • 2021-01-27 07:43

    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!

    0 讨论(0)
提交回复
热议问题