lundi 15 octobre 2018

JS Regex capture between characters OR end of string [duplicate]

This question already has an answer here:

I have a search query in which I'm trying to extract the search terms from, but the regex isn't working exactly as I want.

I have two queries:
First:

?search=mango+pineapple+banana&filter=fruit+berry

Second:

?search=mango

I'm trying to extract the URL between "search=" and & OR the end of the string. Getting the string when the '&' is in the string works like a charm, but if not I would like it to capture 'til the end of the string.

Regex

searchterms = url.match(/\?search=(.*?)&|$/);

The regex I am using returns undefined when not having an ampersand in the URL. Been trying to use different capture groups but i just can't get it to work. Any idea what I'm doing wrong?

Edit: it is not really the same as This link . I tried using the regexp adjusted in the link such as: url.match(/(&|\?search=).*?(&|$)/) but what gets captured is only the "?search=" and not the string after.

Aucun commentaire:

Enregistrer un commentaire