replace segment of a URL with regex - javascript

I have a button that takes a value from a checkbox and inserts it dynamically into a URL parameter. the URL looks like this:
example.com/search?q=searchterm&site=site1&page=1
&site=site1 is what is being updated dynamically by the value of a checkbox. My code for that looked like below at first:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = '&site=' + filterSelection + '&page=1';
console.log(filterUrl + " - " + filterSite);
window.location.replace(filterUrl);
});
The problem with the first approach is when you click the button multiple times, it just adds the new parameters to the URL, so it ends up looking like:
example.com/search?q=searchterm&site=site1&page=1&site=site2&page=1&site=site3&page=1
When I only need to change &site=site3&page=1 - I tried using a regex to select that part of the URL and replace it with the new one. My attempt at that is below:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
console.log(filterUrl + " - " + filterSite);
window.location.replace(url, filterUrl);
});
What this block does is remove the search query and just returns
example.com/site=site1&page=1 which gives a 404.
I need to somehow update a segment of a URL, and not the entire thing. I believe I need to do some sort of regex to target it and change it. What are the next steps? How can I update a certain section of a URL?
EDIT: This is where it stands now:
// apply filter, go to page
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
// console.log(filterUrl + " - " + filterSite);
if (window.location.href.indexOf("&site=") > -1) {
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
window.location.replace(filterSite);
console.log(filterSite);
} else {
window.location.replace(filterUrl);
}
});
but the .replace() method doesn't seem to be working.

Correct me if I got it wrong:
You have something like this: example.com/search?q=searchterm&site=site1&page=1 and you need to update ONLY THIS PART: &site=site1.
One way:
filterSite.replace(/&site=site\d+/,'&site=site' + filterSelection);
This works only if the updatable part of the url is ALWAYS going to be of the form &site=site<number>, ie: filterSelection is always a number
anyhow, let me know
REGARDING YOUR EDIT:
Assuming what you mean by The .replace() method won't change the parameter, is that the URL won't change, you are right: when you do this:
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
what you are modifying is the variable filterSite, the page won't automatically reload to the new url, which I think is what you intend after seeing this other line:
window.location.replace(filterSite);
replace it with:
window.open(filterSite);
to make the page go to the new url
More about window.open and its arguments
One last thing, I noticed you are using /&site=\d+/,'&site=' + filterSelection as args for replace which will not match example.com/search?q=searchterm&site=site1&page=1. So, unless you changed the structure of the url, you might want to look on that too.
let me know

URL Constructor
EXAMPLE: 1
;
var uri = new URL( "http://example.com/search?q=searchterm&site=site1&page=1" );
uri.searchParams.has("q");
>> true
uri.searchParams.set( "site", "site2" );
uri.searchParams.set( "page", "2" );
uri.href;
>> "http://example.com/search?q=searchterm&site=site2&page=2"
;
Browser Suport: ( ? )[ Chrome 49, Firefox 44, Opera 36, IE12 ]

I suggest you to use A POST request method and Jquery has already a method to construct that params to send based in the form
https://api.jquery.com/serialize/

Related

Passing a List<Map> through location.href

My problem is, I want to pass a parameter which is a List to my location.href
function addNewDriver()
{
var pEntityType = <%=c.WIDOC_ENTITY_DRIVER%>;
var pListEntities = <%=lListDrivers%>;
location.href= "<%= c.url %>do/user/groupItemForm.step1.jsp?idClient=" + <%=pIdClient%> + "&listEntities:" + pListEntities +
"&idGroup=" + <%=pIdGroup%> + "&entityType=" + pEntityType + "&<%= lBackButtonUrl %>";
}
This is an example in Chrome console.
var pListEntities = [{dniPerson=4444444S, surname2Person=XXX, passportPerson=null, namePerson=XXX, idGroupItem=1, idPk=1111, surname1Person=XXXX};
This is how I think "they" wanted it.
var pListEntities = [{dniPerson:4444444S, surname2Person:XXX, passportPerson:null, namePerson:XXX, idGroupItem:1, idPk:1111, surname1Person:XXXX};
"lListDrivers" is already filled with values of each driver, like dni, name, surname etc.
The problem comes because, to pass this list, values inside can't have an equal, they need a ":", but I don't know any way to change it.
Convert your List<Map> to JSON. you can use Jackson ObjectMapper to convert it and it will change your pListEntities to a JSON object.
Here is one example.

How to change only the second parameter of an onclick function when it's clicked

I have an onclick handler with two parameters. When it's clicked I want to update only the second parameter value. I prefer jQuery.
I have tried all kinds of jQuery combinations.
The included code works but I want to exclude replacing the first parameter.
The link:
<a href="#" id="messageremove" onclick="messageremove('param1', 'param2')"
The jQuery code:
$("#messageremove").attr('onclick', 'messageremove(' + "'" + param1 + "'" + ', ' + "'" + param2_new + "'" + ')');
I want to exclude replacing the first parameter, but right now both are being replaced.
Pass the variables, store the before variable and the new variable. Then update accordingly. I just switched them in this exmaple.
let before = '';
let after = '';
function messageremove(param1, param2) {
before = param1;
after = param2;
$("#messageremove").attr('onclick', `messageremove(`+ after + `,` + before + `)`)
console.log($("#messageremove").attr('onclick'))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Switch

Cannot pass URL from JavaScript to PHP in Laravel

I'm trying to get three values from a front-end form in JavaScript and then passing those values to the Laravel controller.
I can get two values (Key and Id) but I cannot get the third value because it is a URL. If I comment the URL variable then I'm getting the rest of the two values (Key and Id) but if I'm passing the URL along other two values then I'm not getting anything in my controller.
I have tried these two JavaScript methods encodeURIComponent() and encodeURI() to encode the https URL given but still no luck.
This is my code in JavaScript:
let get_url = $("#get-url").val();
let get_key = $("#get-key").val();
let get_id = $("#get-area").data('getId');
toastr.remove();
if (get_key) {
var req = new Image();
req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
console.log(req.src);
toastr.success(MEASURE.UTILITIES.translate("success_request_successfully_sent"));
$("#btn-send-data-request").hide();
$("#block_get_url").hide();
$("#block_get_key").hide();
$("#csv_get_request_message").show();
} else {
toastr.error(MEASURE.UTILITIES.translate("error_enter_valid_data"));
}
Your get_url contains a url, which i believe has https:// or http://
This is a problem when you are adding to the API URL you are constructing as adding more / changes the ROUTE.
For example your API URL expects req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
which is something like http://www.laravel.com/api/senddata/123/123/urlhere but you are making is something like http://www.laravel.com/api/senddata/123/123/http://urlhere which means you are altering the ROUTE.
To solve that you can URL Encode the URL before passing it.
Change your code to this should work : let get_url = encodeURIComponent($("#get-url").val());
Reference: https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

Javascript URL Query String Logic

I have an events listing page which can be filtered by type and also by date using query string variables.
I am trying to achieve the following logic using javascript/jQuery.
I have a calendar which fires a function when updated. When fired I need to implement the following logic:
If the current URL contains ?filter= then add &dateStart= to the end of the URL.
If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
If the current URL contains ONLY ?dateStart= then replace it with the new one.
I have tried various methods to achieve this but I keep hitting the problem of appending information to the end of the URL rather than replacing parts of it.
Any help would be appreciated.
Thanks.
You can try something like this:
NOTE: not tested.
var newDateValue;
var myPath = window.location.pathname
//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;
if(containsFilter && !containsAppendedDateStart){
// If the current URL contains ?filter= then add &dateStart= to the end of the URL.
window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){
//If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
newDateValue = 10; // add your new value here
var splittedPathArray = myPath.split("&dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
window.location.replace(newUrl);
}else if(containsDateStart){
// If the current URL contains ONLY ?dateStart= then replace it with the new one.
newDateValue = 15;// add your new value here
var splittedPathArray = myPath.split("?dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}
You can achieve this more easy with native Web API or vanilla javascript than with jQuery. As far as jQuery don't provide any specific function to work with query strings.
The new URLSearchParams object provide a few methods to work more easily with URL query strings. In your case for example you'll need to do something like this:
function updateQueryString(queryString, dateStart) {
var queryString = new URLSearchParams(queryString);
queryString.has('dateStart')
? queryString.set('dateStart', dateStart)
: queryString.append('dateStart', dateStart);
return queryString.toString();
}
for this solution you'll need a polyfill
Sadly this is not yet implemented by the majority of web browsers and you'll need to "polyfill" the URLSearchParams object for this solution to work properly. You'll have to add this line to the <head> section in your html:
<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.14/polyfill.min.js"></script>
You can find more information about the URLSearchParams in the Mozilla Developers Network Documentation, the WHATWG specification for the URL Standard or the specification by the W3C
solution without polyfill
​
If you don't like to use edge features you still can do it without any extra polyfill. It would look like this:
function updateQueryString(queryString, dateStart) {
var qsObject = {};
queryString
.substring(1) // ignore '?'
.split('&').forEach(function (param) {
param = param.split('=');
qsObject[param[0]] = param[1];
});
qsObject['dateStart'] = dateStart;
return '&' + Object.keys(qsObject)
.map(function (key) {
return key + '=' + qsObject[key];
})
.join('?');
}
Call whatever version of the updateQueryString function you rather like this:
updateQueryString(windonw.location.search, dateStart)

Why are there non-breaking spaces in my page title?

I'm injecting a script via JSONP and using it to call a method in my web application like so:
(function jsonp(src){
var b = document.body;
var t = document.title;
var u = encodeURI(document.location.href);
var o = document.getElementById('srv-call');
o && b.removeChild(o);
var s = document.createElement('script');
s.id = 'srv-call';
s.src = src + '?w=' + textSelection + '&cb=autoCall&u=' + u + '&pt=' + t + '&t=' + (new Date().getTime());
b.appendChild(s);
})('http://localhost:8888/wordmark/words/add_word');
Unfortunately, my document.title is getting filled with non-breaking spaces. An example http request is this:
http://localhost:8888/wordmark/words/add_word?w=problems&cb=autoCall&u=http://www.boingboing.net/2010/10/01/kid-demonstrates-eng.html&pt=%E2%80%8BK%E2%80%8Bi%E2%80%8Bd%E2%80%8B%20%E2%80%8Bd%E2%80%8Be%E2%80%8Bm%E2%80%8Bo%E2%80%8Bn%E2%80%8Bs%E2%80%8Bt%E2%80%8Br%E2%80%8Ba%E2%80%8Bt%E2%80%8Be%E2%80%8Bs%E2%80%8B%20%E2%80%8BE%E2%80%8Bn%E2%80%8Bg%E2%80%8Bl%E2%80%8Bi%E2%80%8Bs%E2%80%8Bh%E2%80%8B%20%E2%80%8Bl%E2%80%8Ba%E2%80%8Bn%E2%80%8Bg%E2%80%8Bu%E2%80%8Ba%E2%80%8Bg%E2%80%8Be%E2%80%8B%20%E2%80%8Bi%E2%80%8Bn%E2%80%8B%20%E2%80%8B2%E2%80%8B4%E2%80%8B%20%E2%80%8Ba%E2%80%8Bc%E2%80%8Bc%E2%80%8Be%E2%80%8Bn%E2%80%8Bt%E2%80%8Bs%E2%80%8B%20%E2%80%8B-%E2%80%8B%20%E2%80%8BB%E2%80%8Bo%E2%80%8Bi%E2%80%8Bn%E2%80%8Bg%E2%80%8B%20%E2%80%8BB%E2%80%8Bo%E2%80%8Bi%E2%80%8Bn%E2%80%8Bg&t=1285982312594
The script that is injected in the page has the correct src, but the HTTP request is incorrect. Any idea why these are being inserted and if I have any way to avoid this, other than parsing them out via regex?
Thanks so much for any help you can give.
And I just realized the culprit. I apologize for wasting everyone's time, but in the event anyone else runs across this problem, the issue was the SMRT Safari Extension to alter Safari's URL auto-complete feature. -1 for me for not disabling all extensions and trying multiple browsers. Thanks, all.
Have you tried with decodeURIComponent(t) instead of just t?
s.src = src + '?w=' + textSelection + '&cb=autoCall&u=' + u + '&pt=' + decodeURIComponent(t) + '&t=' + (new Date().getTime());
what you need to do is take the variable t off in your line that says
s.src = src + '?w=' + textSelection + '&cb=autoCall&u=' + u + '&pt=' + t + '&t=' + (new Date().getTime());
so your link would look something like this instead:
http://localhost:8888/wordmark/words/add_word?w=problems&cb=autoCall&u=http://www.boingboing.net/2010/10/01/kid-demonstrates-eng.html&&t=1285982312594
and if you must have the t variable then insert it into the line like so
....(code before) '&pt=' + decodeURIComponent(t) + (code after)......
Hope this helps. thanks
PK
Those are not non-breaking spaces, but zero-width spaces (U+200B). They are normally not visible, and may be present in the original title (for text wrapping, or whatever other reason).

Categories

Resources