0

I have a poorly designed URL query string that I can't easily change e.g.

https://mysite/.shtml?source=999&promotype=promo&cmpid=abc--dfg--hif-_-1234&cm=qrs-stv-_wyx&aff=45628_THIS+IS+Test_Example

I need to extract elements from it e.g. 45628

At the moment I'm using

document.URL.split(/aff=|_/)[5];

But I don't like this solution because if other parts of the URL structure change which is highly likely then my solution will break

Instead what I want to say is

split on "aff=" AND THEN split on "_"

Is there an easy way to do this, looking for a JS answer

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Ricky Doy
  • 51
  • 1
  • 5

3 Answers3

2

Pretty sure you can do it like this:

document.URL.split("aff=")[1].split("_")[0];
Danmoreng
  • 2,367
  • 1
  • 19
  • 32
0

I would start by splitting the string into tokens, if you can. Rather than working with foo=bar&fin=bin, break it down into [['foo', 'bar'], ['fin', 'bin]]. You can do that by splitting on the & and then the splitting each of those on the = character:

const data = 'source=999&promotype=promo&cmpid=abc--dfg--hif-_-1234&cm=qrs-stv-_wyx&aff=45628_THIS+IS+Test_Example';

console.log(data.split('&').map(it => it.split('=')));

Next, take the tokens you want and extract the leading digits:

const data = 'source=999&promotype=promo&cmpid=abc--dfg--hif-_-1234&cm=qrs-stv-_wyx&aff=45628_THIS+IS+Test_Example';

const tokens = data.split('&').map(it => it.split('='));
const [key,val] = tokens.find(([key]) => key === 'aff');
console.log(key, val.match(/[0-9]+/));
ssube
  • 47,010
  • 7
  • 103
  • 140
0

var url = 'https://mysite/.shtml?source=999&promotype=promo&cmpid=abc--dfg--hif-_-1234&cm=qrs-stv-_wyx&aff=45628_THIS+IS+Test_Example';

var re = new RegExp(/aff=(\d+)/); var ext = re.exec(url)[1]; alert(ext)

趙曉明
  • 73
  • 5