I have the following url
http://www.test.info/link/?url=http://www.site2.com
How do I get the value of the url parameter with regular expressions in javascript?
Thanks
function extractUrlValue(key, url)
{
if (typeof(url) === 'undefined')
url = window.location.href;
var match = url.match('[?&]' + key + '=([^&]+)');
return match ? match[1] : null;
}
If you're trying to match 'url' from a page the visitor is currently on you would use the method like this:
var value = extractUrlValue('url');
Otherwise you can pass a custom url, e.g.
var value = extractUrlValue('url', 'http://www.test.info/link/?url=http://www.site2.com
Check out http://rubular.com to test regex:
url.match(/url=([^&]+)/)[1]
Might want to check this: http://snipplr.com/view/799/get-url-variables/ (works without regEx)
This one does use regEx: http://www.netlobo.com/url_query_string_javascript.html
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var param = gup( 'var' );
Well, firstly, is that the whole query string? If so, all you need to do is split on the =:
url.split('=')[1];
Otherwise, you might want to use Jordan's Regex.
On the answer code:
function extractUrlValue(key, url)
{
if (typeof(url) === 'undefined')
url = window.location.href;
var match = url.match('[?&]' + key + '=([^&#]+)');
return match ? match[1] : null;
}
If key is a last parameter in URL and after that there is an anchor - it enter code herewill return value#anchor as a value. # in regexp '[?&]' + key + '=([^&#]+)' will prevent that.
Related
I am trying to select just what comes after name= and before the & in :
"/pages/new?name=J&return_url=/page/new"
So far I have..
^name=(.*?).
I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.
The end case situation would be allowing myself to do a replace statement on this dynamic variable found by 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.
The accepted answer includes the hash part if there is a hash right after the params. As #bishoy has in his function, the correct regex would be
/name=([^&#]*)/
Improving on previous answers:
/**
*
* #param {string} name
* #returns {string|null}
*/
function getQueryParam(name) {
var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
return q && q[1];
}
getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2
here is the full function (tested and fixed for upper/lower case)
function getParameterByName (name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search.toLowerCase());
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
The following should work:
\?name=(.*?)&
var myname = str.match(/\?name=([^&]+)&/)[1];
The [1] is because you apparently want the value of the group (the part of the regex in brackets).
var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'
Here's a single line answer that prevents having to store a variable (if you can't use URLSearchParams because you still support IE)
(document.location.search.match(/[?&]name=([^&]+)/)||[null,null])[1]
By adding in the ||[null,null] and surrounding it in parentheses, you can safely index item 1 in the array without having to check if match came back with results. Of course, you can replace the [null,null] with whatever you'd like as a default.
You can get the same result with simple .split() in javascript.
let value = url.split("name=")[1].split("&")[0];
This might work:
\??(.*=.+)*(&.*=.+)?
Suppose that I have a URL like the following:
http://localhost:8000/intranet/users/view?user_id=8823
Now, all I want to do is to get the value of the URL using JavaScript and parse it, taking the user_id value (which is 8823 in this case) and sending that value through an iframe.
How can I do this?
try this code
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
i found it at How can I get query string values in JavaScript?
Try using window.location.href or document.URL
Do this:
var matches = document.location.search.match( /user_id=(\d+)/ );
if ( matches != null )
{
alert( matches[ 1 ] );
}
matches[ 1 ] will contain the user ID.
document.location.search contains the query string (all of the parameters which follow the '?' including the '?').
var test = "http://localhost:8000/intranet/users/view?user_id=8823";
//var url = document.URL;
var url = test.split("=");
var urlID = url[url.length-1];
document.write(urlID);
window.frames["myIframe"].yourMethod(urlID);
I've the following URL
http://somesite/somepage.aspx
I pass a query parameter value which has another URL with query parameters like this.
http://somesite/somepage.aspx?pageURL=http://someothersite/someotherpage.aspx?param1=value&source=http://anotheronesite/anotherpage
I need to get the pageURL value as the one in the bold letters. But i'm getting
http://someothersite/someotherpage.aspx?param1=value
and i'm not getting the source param. I'm using the following JavaScript function -
function getParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Any ideas?
You need to use URL encoding to encode the parameter. Otherwise & is treated as reserved character and belongs to the "base URL".
have u considered html url encoding the pageURL parameter?
this would greatly simplify your task
I would like to insert a parameter value (AS A NUMBER) found the url into my javascript code.. So basically i have the following url www.rene-zamm.com/mp-dthanks.asp?gglid=123123123
Now i have the following javascript code in the same page and i want that number in the url to be visible also in the javascript code where i have written querydata..:
<script type="text/javascript">
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
try {
var querydata = gup("gglid");
var gwoTracker=_gat._getTracker("UA-1639156-3");
gwoTracker._trackPageview("/" + **querydata** + "/goal");
alert(querydata);
}catch(err){}
</script>
For some reason the querydata is showing as text and not as number.. please help
If you're sure that querydata is going to be a number, just use parseInt(querydata) and it will return a number, integer to be exact
Suppose you have a URL:
http://www.example.com/whatever?this=that&where=when
How would you extract the value of the where parameter (in this case when)?
This is what I came up with -- I'm wondering if there's a better solution:
$.fn.url_param_value = function(param) {
var url = $(this).attr('href');
var regex = new RegExp(param + "=");
return $.grep(url.split("?")[1].split("&"), function(a) {
return a.match(regex);
})[0].split("=")[1];
}
use jquery.query and have fun :)
you can simply use:
var w = $.query.get("where");
If you are left without jQuery, here is a function I use:
function urlParam(name, w){
w = w || window;
var rx = new RegExp('[\&|\?]'+name+'=([^\&\#]+)');
var val = w.location.href.match(rx);
return !val ? '':val[1];
}
w is an optional parameter(defaulted to window) if you need to read iframe parameters.
I use this bit of javascript from Netlobo.com
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
or if you are looking for a plugin, try jQuery URL Parser
*Edit: Hmm, nm I guess TheVillageIdiot's suggestion is the best & easiest for jQuery :P... YAY, I learned something new today :) But you should still check out the plugin, it's nice in that it will return any part of the URL including data from a string.