如何获取URL字符串的特定部分?

时间:2019-02-11 21:05:00

标签: javascript typescript

这是下面console.log的结果:

console.log('subscribe:', event.url);
"https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true"

我要剥离src_1E2lmZHazFCzVZTmhYOsoZbgsrc_client_secret_EVnN8bitF0wDIe6XGcZTThYZ的地方

如何实现?

4 个答案:

答案 0 :(得分:2)

将字符串转换为url,读取路径名,然后在/上分割并取最后两部分。

var str = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true"

const parts = new URL(str).pathname.split('/').slice(-2)
console.log(parts)

答案 1 :(得分:1)

如果查询参数?success=true是可选的(在大多数情况下),则可以

function getSrcAndSecret (url) {
  const pts = /\/(src_[^/?]+)\/(src_client_secret_[^/?]+)/.exec(url);
  return {
    src: pts && pts[1] || "",
    secret: pts && pts[2] || ""
  } 
}

// Demo:
const test1 = getSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true");
const test2 = getSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ");
const test3 = getSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete");

console.log(test1, test2, test3)

答案 2 :(得分:0)

const url = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true";


const res = url.split(/\?|\//g).filter(el => el.startsWith("src"));

console.log(res)

答案 3 :(得分:-1)

  const [a, b] = event.url.split("?")[0].split("/").slice(-2);