Capture value out of query string with regex?
/name=([^&]*)/
- remove the
^
and end with an&
Example:
var str = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);
The better way is to break all the params down (Example using current address):
function getParams (str) {
var queryString = str || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/.*?\?/,"");
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
var url = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];
Update
Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.
Extracting a value from query string using Regex
You can use a capturing group based regex like
[&?]Ntt=((?:%20&%20|[^&])*)
See the regex demo.
Alternatively, you can use a lookbehind based regex like
(?<=[&?]Ntt=)(?:%20&%20|[^&])*
See the regex demo.
Details
(?<=[&?]Ntt=)
- a positive lookbehind that matches a location that is immediately preceded with?
or&
and thenNtt=
(?:%20&%20|[^&])*
- a non-capturing group that matches zero or more occurrences of a%20&%20
substring or any char other than&
.
capture value to the left of querystring using regsub
Try capturing non-dots/questions instead:
regsub(req.url, "^http://.*?/([^?.]+).*$", "\1")
Regex for extracting key-value pair from HTTP Query String
In Alteryx, you may use Tokenize with a regex containing a capturing group around the part you need to extract:
The Tokenize Method allows you to specify a regular expression to match on and that part of the string is parsed into separate columns (or rows). When using the Tokenize method, you want to match to the whole token, and if you have a marked group, only that part is returned.
I bolded the part of the method description that proves that if there is a capturing group, only this part will be returned rather than the whole match.
Thus, you may use
(?:^|[?&])token=([^&]*)
where instead of token
you may use any of the keys the value for which you want to extract.
See the regex demo.
Details
(?:^|[?&])
- the start of a string,?
or&
(if the string is just a plain key-value pair string, you may omit?
and use(?:^|&)
or(?<![^&])
)token
- the key=
- an equal sign([^&]*)
- Group 1 (this will get extracted): 0 or more chars other than&
(if you do not want to extract empty values, replace*
with+
quantifier).
How to extract a value from a URL query string in C#?
token=(\d+)
should do the trick
To cater for aplhas as well you can do either:
token=([a-zA-Z0-9+/=]+)
to explicitly match on the characters you expect. This matches "token=" and then captures all following characters that match the character class, that is, a-z, A-Z, 0-9, +, / and =.
or
token=([^]+)
to match any character except for the ones you know can finish the token. This matches "token=" and then captures all characters until the first &
, #
or the end of the string.
Getting specific value from url query string using Regex in Java
I would probably use URLEncodedUtils
from Appache Commons.
String url = "http://www.website.com/search?productId=1500";
List<NameValuePair> paramsList = URLEncodedUtils.parse(new URI(url),"utf-8");
for (NameValuePair parameter : paramsList)
if (parameter.getName().equals("productId"))
System.out.println(parameter.getValue());
outpit 1500
.
But if you really want to use regex you can try
Pattern p = Pattern.compile("[?&]productId=(\\d+)");
Matcher m = p.matcher(url); // _____________↑ group 1
if (m.find()) // |
System.out.println(m.group(1));
get the value of a query string item in a url using regex for javascript
function qry(sr) {
var qa = [];
for (var prs of sr.split('&')) {
var pra = prs.split('=');
qa[pra[0]] = pra[1];
}
return qa;
}
var z = qry('http://example.com/product.php?action=edit&id=c23_02398105&side=1');
z.id; // c23_02398105
Source
how to get the regex from the query param input where the delimiter is & and even the regex contains &?
It's important to URL encode query parameters before the request is sent. This helps to avoid issues with characters that have special meaning (?
, =
, &
, #
, etc.)
So instead of sending literal ampersand characters &
in the regex, it should be URL-encoded to be %26
instead.
/austin/query.html?dept=([^%26]*)&group=([^%26]*)
When this parsed by the querystring
module, it will automatically be converted back to the ampersand character.
const querystring = require('querystring');
const URL = require('url');
function parseQueryParamsFromUrlPath(urlPath) {
const { query } = URL.parse(urlPath);
return querystring.parse(query);
}
parseQueryParamsFromUrlPath('/austin/query.html?dept=([^%26]*)&group=([^%26]*)');
// Output: { dept: '([^&]*)', group: '([^&]*)' }
Extract querystring value from url using regex
You can try this:
[^?]+(?:\?foo=([^&]+).*)?
If there are parameters and the first parameter is named "foo", its value will be captured in group #1. If there are no parameters the regex will still succeed, but I can't predict what will happen when you access the capturing group. Some possibilities:
- it will contain an empty string
- it will contain a null reference, which will be automatically converted to
- an empty string
- the word "null"
- your app will throw an exception because group #1 didn't participate in the match.
This regex matches the sample strings you provided, but it won't work if there's a parameter list that doesn't include "foo", or if "foo" is not the first parameter. Those options can be accommodated too, assuming the capturing group thing works.
Related Topics
How to Add Many Functions in One Ng-Click
Search Recursively for Value in Object by Property Name
Why Does Isnan(" ") (String with Spaces) Equal False
Google Maps API V3 - Multiple Markers on Exact Same Spot
What Does $.When.Apply($, Somearray) Do
How to Define Setter/Getter on Prototype
Jquery - Script Tags in the HTML Are Parsed Out by Jquery and Not Executed
How to Remove Element from an Array in JavaScript
Convert Js Object to Form Data
Triggering a JavaScript Click() Event at Specific Coordinates
Fix Node Position in D3 Force Directed Layout
How to Send an Ajax Request on a Different Port with Jquery
Incorrect Result in JavaScript Calculation
Javascript: Simple Way to Check If Variable Is Equal to One of Two or More Values