繁体   English   中英

如何在javascript中解析特定查询参数的URL?

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

我将有各种URL都包含相同的查询参数:

https://www.example.com/landing-page/?aid=1234

我想通过在URL中搜索“ aid”查询参数来提取“ 1234”。

JavaScript将在Zapier中运行:

Zapier中的示例javascript块

Zapier注意:我们应该通过设置为名为inputData的变量的对象为您的代码提供什么输入数据(作为字符串)?

我一般没有太多的JavaScript或编码经验,但是最终结果将是4位数的“ aid”值,当通过webhook发布到API时,我将引用该值。

编辑:我检查了类似的答案,并赞赏链接,但是我不确定如何在Zapier中使用提供的答案来利用“ inputData”和“ url”。

Zapier Platform团队的David在这里。

尽管上面的注释将您引向了正则表达式,但我还是建议使用一种更本地的方法:实际解析URL。 Node.js有一个很棒的标准库可以做到这一点:

// 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 }

根据您对要查找的数据始终存在的信心,您可能需要在此处进行一些后备操作,但这可以非常可靠地找到要查找的参数。 您还可以在此代码步骤后加上“ Filter以确保依赖于aid后面的步骤(如果缺少)不会运行。

``让我知道您是否还有其他问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM