my url looks something like this
/myurl?code1=abcde&code2=fghijk&code3=lmnop&code4=qrstu&code5=vwxyz (up to max of 5 code variables)
I have an onclick event where I get the code variable, eg in example above it returns 'fghijk', but I don't know the param, eg code2. So I want to do two things:
1) find and remove the param & value from my url (if my onclick variable returns 'fghijk', in the above example my url becomes, /myurl?code1=abcde&code3=lmnop&code4=qrstu&code5=vwxyz)
2) after this I want to reset the param numbers so that my code params are sequential beginning from 1, so after number 1 above executes my url should become /myurl?code1=abcde&code2=lmnop&code3=qrstu&code4=vwxyz
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url +'contains('+codevar+')') {
// strip the param and variable from the url here
// now reset the url so code params are in number sequence
}
});
you could do something like this:
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url.match(codevar)) {
var queryString = url.substring(url.indexOf("?") + 1);
var params = queryString.split("&");
var codeIndex = 1;
var newQuery = "";
for (var i = 0; i < params.length; i++) {
if (!params[i].match(codevar)) {
newQuery += params[i].replace(/code[0-9]/, "code" + codeIndex);
codeIndex++;
if (i < params.length - 1) {
newQuery += "&";
}
}
}
url = url.replace(queryString, newQuery).replace(/&$/, ""); //new query string with the sequential parameters
}
});
Hope this helps.
Regards,
Marcelo
var codevar = 'fghijk';
var url = $('.myelement a').attr('href');
var param = '&'+url.substring(url.indexOf('?')+1);
url = url.substring(0,url.indexOf('?')+1);
if(param.indexOf(codevar) > -1) {
var arr = param.split("&code");
param = '';
for(var i = 1;i<arr.length;i++){
if(codevar == arr[i].substring(2))
arr.splice(i, 1);
param += 'code'+i+'='+arr[i].substring(2);
if(i != arr.length-1)
param +='&';
}
$('.myelement a').attr('href',url+param);
Example:
http://jsfiddle.net/trevordowdle/b9Hmb/1/
You could split the url with the param as key.
var el = $('.myelement'),
out = $("#output");
el.on('click', function (ev) {
ev.preventDefault();
var href = el.find("a").prop("href"),
param = el.find("span").text(),
idx = href.indexOf(param),
arr = [], url;
if (idx > -1) {
arr = href.split(param); // split href[0] param href[1]
url = arr.join("mynewvalue");
out.text(url);
}
});
DEMO : http://jsfiddle.net/tive/EAsw3/
Related
I have query string is as follows.
Window.location.href = http://192.168.1.25:9990/myprofile?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs
I am trying window.location.search I am getting ?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs
But expected output : IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs I need without ?
Try:
window.location.search.substring(1)
You can use searchParams.get() like this example :
var currentUrl = Window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("myprofile");
Check this link
var urlStr = "http://192.168.1.25:9990/myprofile?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs";
function getqueryString(url) {
var retObj = {};
if (!url) return retObj;
var str = url.split('?')[1];
if (!str) return retObj;
var query = str.split('&');
for (var i = 0; i < query.length; i++) {
var pair = query[i].split('=');
retObj[pair[0]] = pair[1];
}
return retObj;
}
var rsl = getqueryString(urlStr);
console.log(rsl)
You can use this function it takes URL as the parameter and returns Back all the query parameter in an object form
I have this var storing a string that represents a URL full of parameters. I'm using AngularJS, and I'm not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex?
For example I need to remove &month=05 and also &year=2017 from:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
Use the URLSearchParams API:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('month');
params.delete('year')
var newUrl = urlParts[0] + '?' + params.toString()
console.log(newUrl);
The advantage of using this API is that it works with and creates strings with correct percent encoding.
For more information, see MDN Developer Reference - URLSearchParams API.
You can use this function that take 2 parameters: the param you are trying to remove and your source URL:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var url2 = removeParam("month", url);
var url3 = removeParam("year", url2);
console.log(url3);
Alternative solution with a regex
Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))
use:
url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');
Read more regex :)...
function removeParam(name, url){
return url.replace('/((&)*' + name + '=([^&]*))/g','');
}
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
function removeParam(name, _url){
var reg = new RegExp("((&)*" + name + "=([^&]*))","g");
return _url.replace(reg,'');
}
url = removeParam('year', url);
url = removeParam('month', url);
document.getElementById('url-replace').innerHTML = url;
<div id="url-replace"></div>
Using string replace:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var modifiedUrl = url.replace('&month=05','').replace('&year=2017','');
console.log(modifiedUrl);
You can use the library https://www.npmjs.com/package/query-string
Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
Enhnaced #Mistalis's answer.
Return the value of the last occurrence of a param
Remove the ? of the removed param was the only param
Url encoded the query params to ensure browser stately
function pruneParams(key, url) {
var urlParts = url.split('?');
var rtnUrl = urlParts[0];
var paramParts;
var paramValue;
var params_arr = [];
var queryString = decodeURIComponent(urlParts[1] || '');
if (queryString !== '') {
params_arr = queryString.split('&');
for (var i = params_arr.length - 1; i >= 0; --i) {
paramParts = params_arr[i].split('=');
if (paramParts[0] === key) {
paramValue = paramParts[1];
params_arr.splice(i, 1);
}
}
if (params_arr.length) {
var wasEncoded = url.split('&').length < 2;
rtnUrl = rtnUrl + '?' + (wasEncoded ? encodeURIComponent(params_arr.join('&')) : params_arr.join('&'));
}
}
return { url: rtnUrl, [key]: paramValue, paramCount: params_arr.length > 1 };
}
var u1 = 'http://localhost:4200/member/';
var u2 = 'http://localhost:4200/member/?ts=23423424';
var u3 = 'http://localhost:4200/member/?fooo=2342342asfasf&ts=252523525';
var u4 = 'http://localhost:4200/member?foo=234243&ts=234124124&bar=21kfafjasf&ts=223424234&dd=This Is A Line';
var u5 = 'http://localhost:4200/member?foo%3D234243%26ts%3D2242424%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line';
console.log(pruneParams('ts', u1));
console.log(pruneParams('ts', u2));
console.log(pruneParams('ts', u3));
console.log(pruneParams('ts', u4));
console.log(pruneParams('ts', u5));
// {
// url: 'http://localhost:4200/member/',
// ts: undefined,
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/',
// ts: '23423424',
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/?fooo=2342342asfasf',
// ts: '252523525',
// paramCount: false,
// },
// {
// url: 'http://localhost:4200/member?foo=234243&bar=21kfafjasf&dd=This Is A Line',
// ts: '234124124',
// paramCount: true,
// }
// {
// url: 'http://localhost:4200/member?foo%3D234243%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line',
// ts: '2242424',
// paramCount: true,
// }
Taken from #Mistalis answer but tidied up. Useful if URLSearchParams API is not available.
const removeUrlParam = function (url, param) {
var parts = url.split('?')
url = parts[0]
if (parts.length !== 2) return url
var qs = parts[1]
if (qs === '') return url
var params = qs.split('&')
for (var i = params.length - 1; i >= 0; i -= 1) {
var key = params[i].split('=')[0]
if (key === param) params.splice(i, 1)
}
return params.length ? url + '?' + params.join('&') : url
}
var url1 = removeUrlParam('/xxxxx', 'a')
var url2 = removeUrlParam('/xxxxx?a=1', 'a')
var url3 = removeUrlParam('/xxxxx?a=1&b=2', 'a')
console.log(url1, url2, url3)
I have a giving string/url like this
https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables
I need to loop thought each parameter in the url. If the value starts with : this indicated that it is a variable an I will need to change that value dynamically by looking at the corresponding meta attribute that matches that variable.
Here is my code in which loops over an array and sets the value of the parameters.
var baseURL = getBaseURL(url);
var params = getParams(url);
var newParams = $.each(params, function(index, param){
if( param.value.substring(0, 1) == ':'){
var myVar = param.value.substring(1);
param.value = $('meta[name=" + myVar + "']).attr('value');
}
});
var finalURL = baseURL + '?' + jQuery.param( newParams );
function getParams(url){
// This function should return an array of objects. Each object should have 2 properties "value" and "name". The "name" property should be the name of the parameter (ie. var1, var2, var3 .....) and the "value" attribute should contains the value of the parameter (ie. 100, :somevar, :morevariables)
}
function getBaseURL(url){
var cutoff = url.indexOf('?');
if( cutoff > -1){
return url.substring(0, cutoff - 1);
}
return url;
}
I need help converting the parameters of a giving URL to array of object. How can I do this in jQuery?
You dont need jQuery for this one.
function getParams(url) {
var queryString = url.substring(url.indexOf('?') + 1);
var paramsArr = queryString.split('&');
var params = [];
for (var i = 0, len = paramsArr.length; i < len; i++) {
var keyValuePair = paramsArr[i].split('=');
params.push({
name: keyValuePair[0],
value: keyValuePair[1]
});
}
return params;
}
Here is an example using map
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables&test';
function getParamArray(url) {
var queryString = url.substring(url.lastIndexOf("?") + 1);
return queryString.split('&').map(function(sParam) {
var param = sParam.split('=');
return {
name: param[0],
value: decodeURIComponent(param[1])
};
});
}
document.getElementById("output").innerHTML = JSON.stringify(getParamArray(url), null, 2);
<pre id="output"></pre>
With a regular expresion and JSON.parse:
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables';
url = url.replace(/^.*\?/,'');
url = url.replace(/(\w+)=?([\w:]*)/g,'{"name":"$1","value":"$2"}');
url = url.replace(/&/g,',');
var paramsObject = JSON.parse("["+url+"]");
/*
Returns:
Array [{"name":"var1","value":"100"},{"name":"var2","value":":somevar"},{"name":"var3","value":":morevariables"}];
*/
You don't even need JQuery for this.
<script type="text/javascript">
var paramStr = window.location.search;
var params = paramStr.substring(1, paramStr.length).split('&');
var paramList = [];
for (var index=0; index < params.length; index++) {
var param = params[index].split('=');
paramList.push({name: param[0], value: param[1]});
}
</script>
The result:
[Object]0: Object
name: "a"
value: "b"
...
var url=new URLSearchParams(window.location.search);
var params = [];
for(var value of url.keys())
{
params.push({
name: value,
value: url.get(value)
});
}
I want a javascript variable to be what is behind the ?url= in the url..
for example: The current url is
http://mywebsite.com/test/index.html?url=http://www.google.com/
So the variable has to be http://www.google.com/ .
I tried this, but it doesn't work… why ?
var url = document.URL ;
var appname = url.match(?url=(.+))[1];
Thanks.
I think the following will work for you:
function querystring(key) {
var query = window.location.search.substring(1);
var keys = query.split("&");
for (i = 0; i < keys.length; i++) {
var values = keys[i].split("=");
if (values[0] == key) {
return values[1];
}
}
}
var appname = querystring("url");
alert(appname);
Try this:
var regex = /\?url\=(.+)/;
var appname = regex.exec(url)[1];
or even simpler:
var appname = /\?url\=(.+)/.exec(url)[1];
var url = location.search.match(/url=([^&]+)&*.*$/)[1]; // http://www.google.com/
location //location object
.search //the search part in location
.match //return string according to regex given
[1] //second result (result in parenthesis)
//--------Use in a function---------
function getQuery(txt){
var result = location.search.match(new RegExp(txt + "=([^&]+)&*.*$"));
return result === null ? undefined : result[1];
}
http://jsfiddle.net/DerekL/J4FfZ/
As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});