如何从 Javascript 中的 URL 中获取特定项目?

How can I get specific items from a URL in Javascript?

我有一个 URL 喜欢 https://www.some.com/something-else/?utm_source=Google-PageM&utm_medium=Paid&utm_campaign=SEM-Something。该请求是提取 UTM 的值(Google-Page、Paid、SEM-Somethig)以在 post 请求中发送它们。实际上我正在使用这个 Javascript 代码:

const utmSource = location.href.replaceAll('?', '$').
  replaceAll('&', '$').
  split('$').filter(utm => utm.includes('utm_source')).
  map(utm => utm.split('=')).flat()[1];

对于每个 UTM(utm_source、utm_campaign 和 utm_medium),但我认为这可能是更好的方法。

有更好的方法吗?

谢谢大家!

如何将其转换为 URL 并获得 searchParams

const url = new URL("https://www.some.com/something-else/?utm_source=Google-PageM&utm_medium=Paid&utm_campaign=SEM-Something");
console.log(url.searchParams.get("utm_medium"));
   

获取全部searchParams:

const url = new URL("https://www.some.com/something-else/?utm_source=Google-PageM&utm_medium=Paid&utm_campaign=SEM-Something");
const params = new URLSearchParams(url);
url.searchParams.forEach(function (val, key) {
        console.log(key,val)
    });

获取 params 开头为 'utm_':

const url = new URL("https://www.some.com/something-else/?utm_source=Google-PageM&utm_medium=Paid&utm_campaign=SEM-Something");
const params = new URLSearchParams(url);
const paraobject ={}
url.searchParams.forEach(function (val, key) {
if(key.startsWith("utm_"))
    paraobject[key] = val
    });
  console.log(paraobject)
  console.log(paraobject["utm_source"])

get the query parameters有很多方法。然后我只检查 utm_ 前缀,像这样:

const url = 'utm_source=Google-PageM&utm_medium=Paid&utm_campaign=SEM-Something';
const params = new URLSearchParams(url);
let utmParams = {};

for (const [key, val] of params) {

  // check for prefix
  if (key.startsWith('utm_')) {

    // add to a new object array
    utmParams[key] = val;
  }
}

console.log(utmParams);

您只需要参数的值吗?我假设您想要在 post 中使用键和值。 获取所有 usm_* 参数(带有键和值)的一种方法是这样的:

const url = new URL("https://www.some.com/something-else/?utm_source=Google-PageM&utm_medium=Paid&utm_campaign=SEM-Something");
const urlParams = new URLSearchParams(url.search);

const utmParams = Array.from(urlParams.entries()).filter(param => param[0].startsWith("utm"));

/* utmParams:
[Array(2), Array(2), Array(2)]
    0: ['utm_source', 'Google-PageM']
    1: ['utm_medium', 'Paid']
    2: ['utm_campaign', 'SEM-Something']
*/

那么,如果您只想获取键或值:

const utmKeys = utmParams.map(key => key[0]);
const utmValues = utmParams.map(value => value[1]);

/* utmKeys:
['utm_source', 'utm_medium', 'utm_campaign']
*/

/* utmValues:
['Google-PageM', 'Paid', 'SEM-Something']
*/