如何在 javascript 中解析特定查询参数的 URL? [英] How do I parse a URL for a specific Query Paramter in javascript?

查看:38
本文介绍了如何在 javascript 中解析特定查询参数的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I will have a variety of URLs that all contain the same Query Parameter:

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

我想通过在 URL 中搜索aid"查询参数来提取1234".

I would like to extract the "1234" by searching for the "aid" query parameter in the URL.

javascript 将在 Zapier 中运行:

The javascript will run in Zapier:

Zapier 中的 javascript 块示例

Zapier 说明:我们应该通过设置为名为 inputData 的变量的对象向您的代码提供哪些输入数据(作为字符串)?

Zapier notes: What input data should we provide to your code (as strings) via an object set to a variable named inputData?

我对 javascript 或一般编码没有太多经验,但最终结果将是 4 位aid"值,然后我会在通过 webhook 发布到 API 时引用该值.

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.

我检查了类似的答案并感谢链接,但是我不确定如何在提供的答案中使用 Zapier 中的inputData"和url".

推荐答案

这里是 David,来自 Zapier 平台团队.

David here, from the Zapier Platform team.

虽然上面的评论指向正则表达式,但我推荐一种更原生的方法:实际解析 url.Node.js 有一个很棒的标准库可以做到这一点:

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 }

根据您对要查找的数据始终存在的信心程度,您可能需要在此处进行一些回退,但这将非常可靠地找到您要查找的参数.您还可以使用 Filter 执行此代码步骤,以确保依赖 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!

这篇关于如何在 javascript 中解析特定查询参数的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆