4

in Javascript i tried to read window.location.search. value of this variable could be something like ?ref=somestring&read=1 or ?read=1&ref=sometring or just ?ref=somestring.

how to extract only ref=somestring from the variable?

so far i 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

2 Answers 2

4

You can use:

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

RegEx Demo

This regex firs matches: ? or & followed by literal text ref= followed by [^&]+ and groups ref[^&]+ in group #1.

Sign up to request clarification or add additional context in comments.

Comments

0

Try

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

or

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

REGEX DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.