Get regex string

in javascript i tried to read window.location.search. the value of this variable may be something like ?ref=somestring&read=1or ?read=1&ref=sometringor just ?ref=somestring.

How to extract from a variable only ref=somestring?

so far I have tried the following regex:

ref.match(/ref=([^\&].*)\&/) // works when ?ref=somestring&read=1
ref.match(/ref=([^\&].*)\&/) // not working when only ?ref=somestring
ref.match(/ref=([^\&].*)\&?/) // works when ?ref=somestring
ref.match(/ref=([^\&].*)\&?/) // works but took all part if ?ref=somestring&read=1
+4
source share
2 answers

You can use:

var m = (ref.match(/[?&](ref[^&]+)/) || ['', ''])[1];

RegEx Demo

This number of regular expressions corresponds to: ?or &, followed by literal text ref=, and then [^&]+groups ref[^&]+in the group #1.

+4
source

Try

ref.match(/(ref=[^\&]*)/) //for ref=somestring

or

ref.match(/ref=([^\&]*)/) //for somestring

REGEX DEMO

0
source

Source: https://habr.com/ru/post/1567983/


All Articles