user3421904
user3421904

Reputation:

regular expression - until you reach a specific character

So for www.test.com?pageToken=xyz&foo=bar I want to get pageToken and its value until &; I have tried /(pageToken=).*[^&]/g but still it is getting all pageToken=xyz&foo=bar instead of just pageToken=xyz. what am I doing wrong?

Upvotes: 1

Views: 40

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You regex is too greedy because of .*. However, for getting param values you can use specific function. Here is one you can use:

function getParameterByName(location, name) {
        name = name.replace(/\]/g, "\\\]").replace(/\[/g, "\\\[");
        var regex = new RegExp("[\/\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    document.getElementById("res").innerHTML = getParameterByName("www.test.com/pageToken=xyz&foo=bar", "pageToken");
<div id="res" />

Just change name to get the required param value from the strings like yours.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You need remove the in-between .* which greedily matches any character zero or more and then use negated character class [^&]* to match any character but not of &, zero or more times.

(pageToken)=([^&]*)

DEMO

Upvotes: 2

Related Questions