I cannot find out the regex to get param value from the part of query string:
I need to send parameter name to a method and get parameter value as result for string like
"p=1&qp=10".
I came up with the following:
function getParamValue(name) {
var regex_str = "[&]" + name + "=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
// check if result found and return results[1]
}
My regex_str now doesn't work if name = 'p'. if I change regex_str to
var regex_str = name + "=([^&]*)";
it can return value of param 'qp' for param name = 'p'
Can you help me with regex to search the beginning of param name from right after '&' OR from the beginning of a string?
This might work, depending on if you have separated the parameter part.
var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";
Looks like split will work better here:
var paramsMap = {};
var params = string.split("&");
for (var i = 0; i < params.length; ++i) {
var keyValue = params[i].split("=", 2);
paramsMap[keyValue[0]] = keyValue[1];
}
If you desperately want to use a regex, you need to use the g flag and the exec method. Something along the lines of
var regex = /([^=]+)=([^&]+)&?/g;
var paramsMap = {};
while (true) {
var match = regex.exec(input);
if (!match)
break;
paramsMap[match[1]] = match[2];
}
Please note that since the regex object becomes stateful, you either need to reset its lastIndex property before running another extraction loop or use a new RegExp instance.
Change your regex string to the following:
//pass the query string and the name of the parameter's value you want to retrieve
function getParamValue(my_query_string , name)
{
var regex_str = "(?:^|\&)" + name + "\=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
try
{
if(results[1] != '')
{
return results[1];
}
}
catch(err){};
return false;
}
Related
I have this string
/results?radius=4000&newFilter=true
and I need to replace radius=4000 with radius=n where n is a variable.
How can I use String.replace() method with regex to match that part?
You can use /radius=\d+/ to match "radius=" followed by any number of digits. With this we can use the replace() method to replace it with the desired value:
var str = "/results?radius=4000&newFilter=true";
var replacement = 123;
var newStr = str.replace(/radius=\d+/, "radius=" + replacement);
console.log(newStr);
If you want to get all parameters you can try this :
function getParams(uri) {
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(uri)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
var str='/results?radius=4000&newFilter=true';
str = str.substring(str.indexOf("?"));
params = getParams(str);
console.log(params);
console.log('radius => ', params['radius']);
This answer is from this post: How to get the value from the GET parameters?
It should be as easy as
var str='/results?radius=4000&newFilter=true';
var n = 1234;
str = str.replace(/(radius=)(\d+)/, "$1" + n);
var url = "/results?radius=4000&newFilter=true";
// or window.location.href for current url
var captured = /radius=([^&]+)/.exec(url)[1]; // your 4000
var newValue = 5000;
url = url.replace(captured, newValue);
by this way you can use it to get all your requested parameters too
and it is not decimal binded
ES6 with regex using positive lookbehind
const string = '/results?radius=4000&newFilter=true',
n = '1234',
changeRadius = (radius) => string.replace(/(?<=radius=)\d+/, n);
console.log(changeRadius(n));
/* Output console formatting */
.as-console-wrapper { top: 0; }
changeRadius is function that takes one parameter (radius) and performs replacement.
About the regex: \d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.
Other regex
Body of changeRadius() function can be replaced with string.replace(/radius=\d+/, 'radius=' + n). It probably has better performance, but original regex is more direct translation of the problem.
You can use capturing without remembering the match to capture only the numerical value after 'radius='.
var url = "/results?radius=4000&newFilter=true";
var radius = 123;
var newUrl = url.replace(/(?:radius=){1}(\d+)/, radius);
console.log(newUrl); // logs '/results?radius=4000&newFilter=true'0
'
In the below code Im not getting the right result. How can I can do pattern match in javascript?
function getPathValue(url, input) {
console.log("this is path key :"+input);
url = url.replace(/%7C/g, '|');
var inputarr = input.split("|");
if (inputarr.length > 1)
input = '\\b' + inputarr[0] + '\n|' + inputarr[1] + '\\b';
else
input = '\\b' + input + '\\b';
var field = url.search(input);
var slash1 = url.indexOf("/", field);
var slash2 = url.indexOf("/", slash1 + 1);
if (slash2 == -1)
slash2 = url.indexOf("?");
if (slash2 == -1)
slash2 = url.length;
console.log("this is path param value :"+url.substring(slash1 + 1, slash2));
return url.substring(slash1 + 1, slash2);
}
getPathValue("http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1","mountainwithpassid|passid")
Im getting the below output
If I pass mountainwithpassid|accesscode as input Im getting output as
100. Same way if I pass
key :mountainwithpassid|passid value :100 // Expected output 1
If your intention is to simply retrieve the value in the path that follows the input (contained within '/') then you can achieve this with a simpler regular expression. First you will need a method to escape your input string since it contains a pipe character '|' which is translated as OR in regex.
You can use this (taken from https://stackoverflow.com/a/3561711):
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
Then your getPathValue function can look something like:
function getPathValue(url, input) {
var pathValue = null;
var escapedInput = RegExp.escape(input);
// The RegExp below extracts the value that follows the input and
// is contained within '/' characters (the last '/' is optional)
var pathValueRegExp = new RegExp(".*" + escapedInput + "/([^/]+)/?.*", 'g');
if (pathValueRegExp.test(url)) {
pathValue = url.replace(pathValueRegExp, '$1');
}
return pathValue;
}
You will also need to think about how you handle errors - in the example a null value is returned if no match is found.
I'm trying to understand the question. Given a URL of:
"http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1"
and an argument of:
"mountainwithpassid|passid"
you expect a return value of:
"1"
An argument of
"mountainwithpassid|accesscode"
should return:
"100"
Is that correct? If so (and I'm not certain it is) then the following may suit:
function getPathValue(url, s) {
var x = url.indexOf(s);
if (x != -1) {
return url.substr(x).split('/')[1];
}
}
var url = "http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1";
var x = "mountainwithpassid|passid";
var y = "mountainwithpassid|accesscode";
console.log(getPathValue(url, x)); // 1
console.log(getPathValue(url, y)); // 100
How can I replace:
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations(1002)?$expand=Stations";
by:
var nameInstallation = 1002;
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations(nameInstallation)?$expand=Stations";
Why do this the hard way? For this use case, simple concatenation would be very readable:
var nameInstallation = 1002;
var url = 'http://localhost:2879/ServiceDonneesArchive.svc/Installations(' + nameInstallation + ')?$expand=Stations';
Use the .replace() method. To replace any instances of "nameInstallation" in your url variable with "1002":
url = url.replace(/nameInstallation/g, "1002");
Or if you have the replacement value in a variable nameInstallation = 1002:
url = url.replace(/nameInstallation/g, nameInstallation);
EDIT: As pointed out by David Thomas, you probably don't need the g flag on the regular expression that is the first parameter to .replace(). With this "global" flag it will replace all instances of the text "nameInstallation". Without the flag it would replace only the first instance. So either include it or leave it off according to your needs. (If you only need to replace the first occurrence you also have the option of passing a string as the first parameter rather than a regex.)
Try it out this javascript function
// from http://www.codeproject.com/Tips/201899/String-Format-in-JavaScript
String.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
and use:
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations{0}?$expand=Stations";
var nameInstallation = 1002;
var result = url.format(nameInstallation );
How to extract the query string from the URL in javascript?
Thank you!
You can easily build a dictionary style collection...
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
And use it like this...
var qs = getQueryStrings();
var myParam = qs["myParam"];
If you're referring to the URL in the address bar, then
window.location.search
will give you just the query string part. Note that this includes the question mark at the beginning.
If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:
url.substring(url.indexOf("?"))
That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.
Here's the method I use...
function Querystring() {
var q = window.location.search.substr(1), qs = {};
if (q.length) {
var keys = q.split("&"), k, kv, key, val, v;
for (k = keys.length; k--; ) {
kv = keys[k].split("=");
key = kv[0];
val = decodeURIComponent(kv[1]);
if (qs[key] === undefined) {
qs[key] = val;
} else {
v = qs[key];
if (v.constructor != Array) {
qs[key] = [];
qs[key].push(v);
}
qs[key].push(val);
}
}
}
return qs;
}
It returns an object of strings and arrays and seems to work quite well.
(Strings for single keys, arrays for the same key with multiple values.)
You need to simple use following function.
function GetQueryStringByParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
--- How to Use ---
var QueryString= GetQueryStringByParameter('QueryString');
Very Straightforward!
function parseQueryString(){
var assoc = {};
var keyValues = location.search.slice(1).split('&');
var decode = function(s){
return decodeURIComponent(s.replace(/\+/g, ' '));
};
for (var i = 0; i < keyValues.length; ++i) {
var key = keyValues[i].split('=');
if (1 < key.length) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
There is a new API called URLSearchParams in browsers which allow you to extract and change the values of the query string.
Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.
Initialize/Input
To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1) on the querystring, as Jake Archibald suggests:
var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12
In later implementations, you should be able to use it without slice:
var params = new URLSearchParams(window.location.search); // myParam=12
Get
You can get params from it via the .get method:
params.get('myParam'); // 12
Set
Params can be changed using .set:
params.set('myParam', 'newValue');
Output
And if the current querystring is needed again, the .toString method provides it:
params.toString(); // myParam=newValue
There are a host of other methods in this API.
Polyfill
As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).
Works for me-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
You can use this Javascript :
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
OR
You can also use the plugin jQuery-URL-Parser allows to retrieve all parts of URL, including anchor, host, etc.
Usage is very simple and cool:
$.url().param("itemID")
via James&Alfa
I have use this method
function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx.
How do I get the dest variable in JavaScript?
Here is a fast and easy way of parsing query strings in JavaScript:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Now make a request to page.html?x=Hello:
console.log(getQueryVariable('x'));
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2 into object {hello: 1, another: 2}. From there, it's easy to extract the variable you need.
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3". To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.
You can also use the excellent URI.js library by Rodney Rehm. Here's how:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
And to parse the query string of current page:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...
'use strict';
function parseQuery(search) {
var args = search.substring(1).split('&');
var argsParsed = {};
var i, arg, kvp, key, value;
for (i=0; i < args.length; i++) {
arg = args[i];
if (-1 === arg.indexOf('=')) {
argsParsed[decodeURIComponent(arg).trim()] = true;
}
else {
kvp = arg.split('=');
key = decodeURIComponent(kvp[0]).trim();
value = decodeURIComponent(kvp[1]).trim();
argsParsed[key] = value;
}
}
return argsParsed;
}
parseQuery(document.location.search);
Following on from my comment to the answer #bobby posted, here is the code I would use:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)
If you know that you will only have that one querystring variable you can simply do:
var dest = location.search.replace(/^.*?\=/, '');
The following function will parse the search string with a regular expression, cache the result and return the value of the requested variable:
window.getSearch = function(variable) {
var parsedSearch;
parsedSearch = window.parsedSearch || (function() {
var match, re, ret;
re = /\??(.*?)=([^\&]*)&?/gi;
ret = {};
while (match = re.exec(document.location.search)) {
ret[match[1]] = match[2];
}
return window.parsedSearch = ret;
})();
return parsedSearch[variable];
};
You can either call it once without any parameters and work with the window.parsedSearch object, or call getSearch subsequently.
I haven't fully tested this, the regular expression might still need some tweaking...
How about this?
function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = queryStr.replace(regex, "$1");
// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}
..then just call it with:
alert('Var "dest" = ' + getQueryVar('dest'));
Cheers
I wanted a simple function that took a URL as an input and returned a map of the query params.
If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.
This should work back and for with the jQuery.param( qparams ) function.
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page
Head
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">