How to replace query parameter in URL using Regex? - javascript

I have to use regular expressions to replace or append a query to a url with the function adjustUrlParameter(url, param). If the same query exists in the URL, it should replace the query with param (i.e. ID=501 should replace ID=200 in google.com?ID=200). If no query exists, it should simply append the query to the end of the url. Finally, if a query does exist but of a different type, it should append the query and separate it from the pre-existing query with a '&'. Here's an example:
adjustUrlParameter('google.com?ID=501', 'TYPE=444') // => 'google.com?ID=501&TYPE=444'
My code isn't replacing the same query type. It is returning 'google.com?ID=501&ID=200' instead of returning 'google.com?ID=200'. Here's my code:
var adjustUrlParameter = function(url, param) {
var urlQuery = url.match(/\w+\W+/g);
for (var i = 0; i < urlQuery.length; i++) {
if (param === urlQuery[i]) {
return url.replace(/\?.+$/, '?' + param);
}
}
if (url.match(/\?/)) {
return url + "&" + param;
} else {
return url + "?" + param;
}
};
How do I get adjustUrlParameter('google.com?ID=501', 'ID=201') to return the proper result ('google.com?ID=201')?

The problem is that the if statement never returns true. Put some console.logs in the for loop and watch it. You'll see when urlQuery[i] returns "ID=" param returns "ID=444". They are not equal.
console.log("parameter:"+param); //parameter:ID=444
console.log("url_query: "+urlQuery[i]); //url_query: ID=
If you change your for loop like below it replaces the query parameter with the same type:
for (var i = 0; i < urlQuery.length; i++) {
console.log("parameter:"+param);
console.log("url_query: "+urlQuery[i]);
var paramType = param.split("=");
console.log("paramType"+paramType);
var tmp = paramType[0]+"="; //since urlQuery[i] always has a character at the end
console.log(tmp);
if (tmp === urlQuery[i]) {
return url.replace(/\?.+$/, '?' + param);
}
}
When you run adjustUrlParameter('google.com?ID=501', 'ID=444') the output is "google.com?ID=444"

You want to compare the names of the queries, not the values they contain too.
Say you pass in id=200 as param, you want to find and replace from id in the existing url. That means that we don't care about the value of id. If that is the case, we can split by ? or & to get a list of all of the queries. We start looping at 2 because 0 and 1 are the base url and the ?. We also jump 2 with every iteration to skip the preceding &. Lastly, we make sure to split each query with = and use [0] or the first half to get that name that we care about.
You could do something like this:
var adjustUrlParameter = function(url, param) {
var urlQuery = url.split(/(\?|\&)/)
, thisQuery = param.split(/\=/)[0]
for (var i = 2; i < urlQuery.length; i = i + 2) {
if (thisQuery === urlQuery[i].split(/\=/)[0]) {
return url.replace(/(\?|\&).*$/, '?' + param);
}
}
if (url.match(/\?/)) {
return url + "&" + param;
} else {
return url + "?" + param;
}
};

Related

Replace value of id in URL

I have URLs of that form:
https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es
I would like, via javascript to replace 9616071454 with 1, for example.
I know about the replace(), but this will replace "id" itself, not the value of "id".
Is there anything common in the web dev world? :)
The solution considering situations when:
id param can contain other characters besides digits
avoiding fragment # replacement when id is followed by #
var str = 'https://www.foo.com/bar?trump=15&hilarry=es&id=961607some1454text#fragment',
newId = 1,
replaced = str.replace(/\bid=[^&#]+/g, "id=" + newId);
console.log(replaced); // "https://www.foo.com/bar?trump=15&hilarry=es&id=1#fragment"
Simply hard-code that &id= to be re-replaced.
var str = 'https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es';
var str2 = 'https://www.merkel.com/obama?id=9616071454&trump=15&hilarry=es';
var newId = '123';
str = str.replace(/([&?])id=[0-9]+/, '$1id=' + newId);
str2 = str2.replace(/([&?])id=[0-9]+/, '$1id=' + newId);
alert(str);
alert(str2);
Its simple pattern matching. You can refer to this URL about pattern matching.
function(newValue,url) {
url=url.replace(/id=\d+/,'id='+newValue);
return url;
}
This function works and it allows you to pick way parameter you want.
var exampleStrng ='trump=15&id=9616071454&hilarry=es'; // this is an example query string.
var urlQry = window.document.location.search.substring(1); // you can use this in live code to get the query string.
// reusable function for split in text.
function strSpliter( str, splitVal ){
return str.split(splitVal);
}
// function to reassign query parameter values.
function changQry(qry, setParam, chngVal){
var pnt = strSpliter(qry, '&'),//use the spliter function to change the query into an array split on the '&' character.
newQryArr = [], // a temp array to hold the new parameters and their value.
newQry = '',// this will be the string where the query parameters and values are reconstructed into a string.
newQryStr = '';// this will be the query with the new value.
pnt.forEach( function( item, idx ){
var param = strSpliter(item, '='); //use the spliter function to split the parameter and their value.
// checks the parameter against the one you want to change.
if( param[0] === setParam ){
param[1] = chngVal;// assigns the new value to the parameter.
newQryArr.push(param.join('=')); // rejoins the parameter and its value and pushes it into the temp array.
} else {
newQryArr.push(param.join('='));// rejoins the parameter and its value and pushes it into the temp array.
}
newQry = newQryArr.join('&');// rejoins all the parameters and their values.
newQryStr = '?' + newQry;// creates the new query string.
});
return newQryStr; // returns the new search query string.
}
changQry(exampleStrng, 'id', 77777745);
without comments
var urlQry = window.document.location.search.substring(1);
function strSpliter( str, splitVal ){
return str.split(splitVal);
}
function changQry(qry, setParam, chngVal){
var pnt = strSpliter(qry, '&'),
newQryArr = [],
newQry = '',
newQryStr = '';
pnt.forEach( function( item, idx ){
var param = strSpliter(item, '=');
if( param[0] === setParam ){
param[1] = chngVal;
newQryArr.push(param.join('='));
} else {
newQryArr.push(param.join('='));
}
newQry = newQryArr.join('&');
newQryStr = '?' + newQry;
});
return newQryStr;
}
changQry(urlQry, 'id', 77777745);

JavaScript get url segment and parameter

I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)

How can I remove certain elements of a query string?

I'm working on a script, where you pass it a url like /search?filter1=question-1&filter2=question2, and when either question-1 or question-2 is changed, it will take the url, and replace the question-x with the question value.
One thing I want to build in, is if the value is empty, I want it to remove the query string part. So for example, if question-1 has a value of something, but 2 doesn't have a value yet, the url will be /search?filter1=something.
What I thought would work would be something like this
$url.match('/([^?&]*)' + name.toSearch + '/g') // toSearch is a value like question-1
But that returns null. Can anybody help me figure out what I need to change to get the output I'm after?
Given the url /search?filter=question-1, I need to see if the element with the name question[1] has a value, if it does, replace question-1 with the value, and if it doesn't have one, remove the total filter=question-1 string.
Knowing your requirements better from the comments, I completely rewrote my answer using parts of my original answer and some of your code:
// Given url
var url = '/search?filter1=question-1&filter2=question-2';
// Specify the filters so no extra query string noise enters the final url
var filters = ["filter1", "filter2", "filter3"];
// Split the query string parts
var urlParts = url.split(/([&?])/);
var reassembled = [];
// Break the url parts into key:value pairs
var qs = (function(a) {
if (a === "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(urlParts);
// This include a param:value in the reassembled array
function includeQSParam(param, value) {
if(qs[param]) {
reassembled.push(param + "=" + value);
}
}
// Run through the filters
for(var ind in filters) {
var filter = filters[ind];
// Check that the filter exists and the supplied value is of type question-
if(qs[filter] && qs[filter].indexOf("question-") >= 0) {
// Turns question-number into question[number] so it's a valid selector.
var inputSelector = "question["+(qs[filter]).replace(/\D/g, "")+"]";
// Get the input, and the value (author-supplied code)
var $input = $('[name="' + inputSelector + '"]');
// TODO: confirm this is how you get the value
var value = $input.closest('.question').val();
if($input.length > 0 && (value !== '' && value !== undefined)) {
// Replace the parameter's original value with the question value
includeQSParam(filter, value);
} else {
// Nothing to do. This filter will be removed automatically
}
}
}
// Reassemble the URL
var fixedUrl = urlParts[0] + (reassembled.length > 0 ? "?"+reassembled.join("&") : "");
Again, this was reworked from my original answer so there will be some bloat, but I didn't want to abandon the question on you.
Whilst Drakes answer is a good one, it didn't quite fit into my needs. I've ended up with this, which works well so far, but I'm still testing it.
var $url = '/search?filter1=question-1&filter2=question-2';
// Break the url into parts.
var $split = $url.split(/([&?])/);
$.each($split, function(indexToRemove, part){
// If the part is a question.
if(typeof part == 'string' && part.indexOf('question-') > -1){
var $number = part.split('=');
// Turns question-number into question[number] so it's a valid selector.
$inputSelector = String($number[1]).replace('-', '[') + ']';
// Get the input, and the value.
var $input = $('[name="' + $inputSelector + '"]');
var $value = getValue($input.closest('.question'));
// If there is an element, and there is a value.
if($input.length > 0 && ($value != '' && $value != undefined)){
$split[indexToRemove] = part.replace($number[1], $value);
} else {
$split.splice(indexToRemove, 1);
}
}
});
$url = $split.join('');
// If for example question-1 has a value of 'Test', and question-2 has no value, $url will now be '/search?filter1=Test'.

Remove a Particular Query string from URL [duplicate]

This question already has answers here:
How can I delete a query string parameter in JavaScript?
(27 answers)
Closed 8 years ago.
I am trying to create a function to remove a particular querystring and its value from the url .
For eg:
if i have a url like
var url = www.foo.com/test?name=kevin&gender=Male&id=1234
If i pass name -> it should remove the key and value for name. the url should become
www.foo.com/test?gender=Male&id=1234
i have a Function ReturnRefinedURL(key,url)
and i am doing this in the Function
function ReturnRefinedURL(key,url)
{
var Value = getParameterByName(key); // This returns kevin
var stringToBeRemoved = 'key +'='+ Value+'&'; // string becomes 'name=kevin&'
return url.replace(stringToBeRemoved, '');
}
//Found this in Google:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
So when i call the method ReturnRefinedURL('name',window.location.href);
This works!!! But looking for a more elegant and fool proof method.
* This wont work if name parameter is the second one in the query string. (the '&' will still be retained)
Little bit of more search and then you can end up here:
var url = "www.foo.com/test?name=kevin&gender=Male&id=1234";
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0]+'?'+pars.join('&');
return url;
} else {
return url;
}
}
console.log(removeURLParameter(url, 'name'));
console.log(removeURLParameter(url, 'gender'));
Jsfiddle example
You can simply do this
function returnRefinedURL(key, url){
return url.replace(new RegExp(key + "=\\w+"),"").replace("?&","?")
.replace("&&","&");
}
Tested all the use-cases and the above works perfectly.
I'd suggest:
// obviously in real use, you could just access 'document.location'
// within the function:
function returnRefinedURL (key, url) {
// separating the key-value ('search') portion of the URL from the rest:
var urlParts = url.split('?');
// if we have only a single array-element, or if the key to remove
// is not found in the URL, we quit here and return the same unchanged URL:
if (urlParts.length === 1 || url.indexOf(key) === -1 ) {
// there were no parameters, or the
// key wasn't present
return url;
}
else {
// otherwise, we split the key-value string on the '&' characters,
// for an array of key=value strings:
var keyValues = urlParts[1].split('&'),
// filtering that array:
refinedKeyValues = keyValues.filter(function (keyValuePair) {
// keeping only those array elements that don't /start with/
// the key to be removed:
return keyValuePair.indexOf(key) !== 0;
// joining the key=value pairs back into a string:
}).join('&');
}
// returning the refined URL:
return urlParts[0] + '?' + refinedKeyValues;
}
// beyond this point is entirely irrelevant, it's just for visual feedback:
document.getElementById('output').textContent = returnRefinedURL('name', 'www.foo.com/test?name=kevin&gender=Male&id=1234');
#output::before {
content: 'output: ';
}
<div id="output"></div>
References:
Array.prototype.filter().
Array.prototype.join().
String.prototype.indexOf().
String.prototype.split().

Get escaped URL parameter

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.
?search=%E6%F8%E5
The value of the URL parameter, when decoded, should be:
æøå
(the characters are Norwegian).
I don't have access to the server, so I can't modify anything on it.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
Blog post: http://blog.weareon.net/working-with-url-parameters-in-javascript/
Code: http://pastebin.ubuntu.com/1163515/
You can use the browser native location.search property:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
But there are some jQuery plugins that can help you:
query-object
getURLParam
Based on the 999's answer:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Changes:
decodeURI() is replaced with decodeURIComponent()
[?|&] is added at the beginning of the regexp
Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
After reading all of the answers I ended up with this version with + a second function to use parameters as flags
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.
I've created a tiny module that can parse the query string into an object. Use it like this:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:
/*
* #param string parameter to return the value of.
* #return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id) or getURLParameter(Id) Works the same : )
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18
Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
Slight modification to the answer by #pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
This may help.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>

Categories