-1

Having a little trouble with targeting "group of characters that might contain a hypen before" with regex. I'm performing this on a string of query params. I might have something like this:

http://www.example.com?page=5&items=ASC&state=NY

I'm trying to find all the characters before =ASC, so in this case it would be items.

Because items is dynamic, this could change, so would like to be able to target any word that could be placed before =ASC (including hyphens).

Here are a few examples of other cases I need to meet:

http://www.example.com?status=ASC&state=HI

Should capture status

http://www.example.com?page=5&e-mail=ASC&state=NY

Should capture e-mail

I currently have:

const url = 'http://www.example.com?page=5&items=ASC&state=NY';
const newUrl = url.replace(/[a-zA-Z0-9-]=(?=ASC)/, 'test');

but it's not working.

Any and all help would be greatly appreciated.

dace
  • 5,819
  • 13
  • 44
  • 74
  • 1
    Instead of doing this with regex, you should [parse the URL](https://stackoverflow.com/q/979975/1048572) – Bergi Aug 30 '17 at 22:23
  • @KevinB That's a lookahead expression – Bergi Aug 30 '17 at 22:24
  • 1
    I think you're looking for `/[a-zA-Z0-9-]+(?==ASC)/`. Notice the repetition of the character group, and the equals sign that was moved into the lookahead. – Bergi Aug 30 '17 at 22:26

2 Answers2

0

RegEx is not my strong point.

But I think this does something like what your after..

breakdown..

(&\?) first looks for a ? or &.. this becomes the first capture group. ([a-zA-Z0-9-]*)=ASC is looking for your string=ASC, this becomes the second capture group that we will ignore (&|$) look for & or end of line, 3rd capture group

$1test=ASC$3 = use first capture group, add test=ASC, and then add 3rd capture group..

var
  urls = [
    'http://www.example.com?page=5&items=ASC&state=NY',
    'http://www.example.com?items=ASC&page=5&state=NY',
    'http://www.example.com?page=5&state=NY&items=ASC',
    'http://www.example.com?page=5&e-mail=ASC&state=NY'];
    
urls.forEach((url)=>{
  console.log(url.replace(/(&|\?)([a-zA-Z0-9-]*)=ASC(&|$)/, '$1test=ASC$3'));
});
Keith
  • 22,005
  • 2
  • 27
  • 44
0

If your search text are only urls you can parse it easily.

Something like that:

const urls = [
  'http://www.example.com?page=5&items=ASC&state=NY',
  'http://www.example.com?items=ASC&page=5&state=NY',
  'http://www.example.com?page=5&state=NY&items=ASC',
  'http://www.example.com?page=5&e-mail=ASC&state=NY'
];

const result = urls.map((url) => url.split('?')[1])
  .map((search) => search.split('&')
    .map((parts) => parts.split('='))
    .filter((parts) => parts.indexOf('ASC') > -1)
    .map(ascParts => ascParts[0]));

console.log(result);
felixmosh
  • 32,615
  • 9
  • 69
  • 88