简体   繁体   中英

How to get specific part of url string?

This is the result of the console.log below:

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

Where I want to strip src_1E2lmZHazFCzVZTmhYOsoZbg and src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ

How to achieve this?

Convert the string to a url, read the pathname and than split on / and take the last two parts.

 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) 

If the query parameter ?success=true is optional (as in most cases is ) you could

 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) 

 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) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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