How to modify URL Query String without reload - javascript

I'm using the following method to change the query URL parameter corresponding to the input/dropdown on a form. Currently window.location.href will cause a page reload on change. How can I integrate history.replaceState() instead to modify the URL without reloading?
REGEX function
function replaceQueryString(url, param, value) {
var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
if (url.match(re))
return url.replace(re, '$1' + param + "=" + value + '$2');
else
return url + '&' + param + "=" + value;
}
On input change
$("#input_field").on('change', function(e) {
window.location.href = replaceQueryString(window.location.href, 'input_value', $(this).val());
});
Update
I've now managed to update the URL to the value domain.com/2 on change, but how can I run it through the replaceQueryString function to parse it into domain.com/?input_value=2
$("#input_field").on('change', function(e) {
window.history.replaceState("#input_field", "input_value", $(this).val());
});

Pass replaceQueryString() function to third parameter of .replaceState()
window.history.replaceState({}
, "input_value"
, replaceQueryString(location.href, "input_value", $(this).val()));

Related

How to add parameter in Javascript and remove previous parameter

I had a code that works but the problem is it just append the parameter instead of replacing it with a new parameter, Here is my working code:
jQuery('#input_1_11').change(function(){
var type = jQuery('#input_1_11').val();
if(type=='Inspection'){
window.location.replace(window.location.href + "?Inspection");
}
else if(type=='Installation'){
window.location.replace(window.location.href + "?Installation");
}
else{
window.location.replace(window.location.href + "?Maintenance");
}
});
what currently happening is for example
www.test.com?Inspection
Then if I click again the input11 it goes to the link
www.test.com?Inspection?Maintenance
What I need is to replace each ?parameter every change by user.
use origin:
window.location.origin + "?Maintenance"
instead of
window.location.href + "?Maintenance"
You can do a thing - get the present url and split it into an array with ? as parameter for split. Get the first element of that array. It will be the url without parameters.
jQuery('#input_1_11').change(function(){
var type = jQuery('#input_1_11').val();
var present = window.location.href.split("?");
if(type=='Inspection'){
window.location.replace(present[0] + "?Inspection");
}
else if(type=='Installation'){
window.location.replace(present[0] + "?Installation");
}
else{
window.location.replace(present[0] + "?Maintenance");
}
});

Remove one parameter name and value in url using jquery

Existing Url
http://example.com/home.php?id=1&branch_id=4&course_id=5
New url
http://example.com/home.php?id=1&branch_id=4
removing course_id from existing url
How to remove one parameter value from url.
Tried below code:
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
but its not working...
As you said that you want to use variable instead of directly using .replace(/&course_id=\d+/, ''), you can do it like below:-
Example:-
var re = new RegExp("&course_id=\\d+");
var newUrl="http://example.com/home.php?id=1&branch_id=4&course_id=5";
console.log(newUrl.replace(re, ''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can simply do that by using this code to remove &course_id=5:
var url = "http://example.com/home.php?id=1&branch_id=4&course_id=5";
url.replace(/([&\?]course_id=5*$|course_id=5&|[?&]course_id=5(?=#))/, '');
It will return you: http://example.com/home.php?id=1&branch_id=4

Make word in into a link jQuery

I'm trying to make this:
<td class="Monthly Status-cell">/fileid=XXXX</td>
Display as
http://www.domain.com/fileid=XXXX
Can you tell me what is wrong with my code?
$('.Status-cell').replaceWith(function() {
var url = $.trim($(this).text());
return '' + url + '';
});
Thanks!
Use .html() instead of .replaceWith(). While using replaceWith you are replacing the td with anchor inside your table, which is invalid and that must be causing your alignment to get messed up.
$('.Status-cell').html(function(_, currentText) {
var url = "http://www.domain.com" + $.trim(currentText);
return '' + url + '';
});
Fiddle
Rather than replace the td with a link you should place the link in the td. Also you didn't add the domain to the link
$('.Status-cell').html(function() {
var url = window.location.protocol+'//'+window.location.host+$.trim($(this).text());
return '' + url + '';
});
http://jsfiddle.net/bUpYE/1/
Try
$('.Status-cell').html(function(idx, value){
value = $.trim(value);
return 'http://www.domain.com' + value + '';
})
Demo: Fiddle
Place the link in the cell using .html() instead of .replaceWith():
var domain = window.location.hostname; // current domain
$('.Status-cell').html(function(i, value) {
var link = domain + $.trim(value);
return '' + link + '';
});
http://jsfiddle.net/samliew/ZUYCX/

add parameter to links on page using jquery

How do I add let's say something like ajax=1 to all links on my page with jquery. I will also need to check if the url has existing parameters. for example http://example.com/index.php?pl=132 will have to become http://example.com/index.php?pl=132&ajax=1
Also, if the link does not have any parameters, for example http://example.com/index.php, it will become http://example.com/index.php?ajax=1 I want to load the jQuery script on document ready so all links are changed on page load.
You could do something like this:
$(function() {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&ajax=1" : "?ajax=1");
});
});
On document.ready this looks at every <a>, looks at it's href, if it contains ? already it appends &ajax=1 if it doesn't, it appends ?ajax=1.
Like this:
$(function() {
$('a[href]').attr('href', function(index, href) {
var param = "key=value";
if (href.charAt(href.length - 1) === '?') //Very unlikely
return href + param;
else if (href.indexOf('?') > 0)
return href + '&' + param;
else
return href + '?' + param;
});
})
Here is a solution I put together for native Javascript, it supports existing query strings and anchors:
function addToQueryString(url, key, value) {
var query = url.indexOf('?');
var anchor = url.indexOf('#');
if (query == url.length - 1) {
// Strip any ? on the end of the URL
url = url.substring(0, query);
query = -1;
}
return (anchor > 0 ? url.substring(0, anchor) : url)
+ (query > 0 ? "&" + key + "=" + value : "?" + key + "=" + value)
+ (anchor > 0 ? url.substring(anchor) : "");
}
I've posted my existing tests on JSBin: http://jsbin.com/otapem/2/
If you're interested in plugins, there's the jQuery Query String Object. This will allow you simple checking of parameters in the querystring, and if necessary the ability to add more, remove some, or edit others.
Taking what is above, this is the best way to concatenate parameters to links.
Also avoid link with href like href="Javascript:YourFunction();"
$(function(){
var myRandom = getRandom();
$('a[href]').each(function(i){
var currHref = $(this).attr("href");
var isAfunction = currHref.substring(0,10);
if(isAfunction == "javascript"){
$(this).attr("href",currHref);
}else{
if (currHref.charAt(currHref.length - 1) === '?')
$(this).attr("href",currHref);
else if (currHref.indexOf('?') > 0)
$(this).attr("href",currHref+"&rand="+getRandom());
else
$(this).attr("href",currHref+"?rand="+getRandom());
}
});
});
function getRandom(){
var randomnumber = Math.floor(Math.random()*10000);
return randomnumber;
}
a href must be full and corrected URL.
$(function() {
$('a[href]').attr('href', function(index, href) {
var url = new URL(href);
url.searchParams.set('ajax',1);
return url;
});
})
JSFiddle

How would I remove from spaces from a search form using jQuery?

I've replaced the submit URL from the search form with this jQuery snippet:
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
window.location.href = "/search-" + $('.search-form input:text').val() + "-" + "keyword"+ "-"+ "keyword2/" + $('.search-form input:text').val() + ".html";
return false;
});
});
</script>
This works fine and turns the URL into a nice SEO cleaned URL. But how can I replace the spaces?
When someone types in "search me" the URL looks like /search-search me-keyword-keyword2/search me.html with spaces. With + or - it would look much better. I know of str_replace from PHP, but how would I go about this in jQuery?
There's a native JavaScript function called encodeURIComponent that's intended to do exactly what you need.
window.location.href =
"/search-" +
encodeURIComponent($('.search-form input:text').val()) +
"-" + "keyword" + "-" + "keyword2/" +
encodeURIComponent($('.search-form input:text').val()) +
".html";
Method 1: Using Replace
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
var value = $('.search-form input:text').val();
value = value.replace(' ', ''); // replace
window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
return false;
});
});
</script>
Method 2: Encoding URL
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
// encode url
var value = encodeURIComponent($('.search-form input:text').val());
window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
return false;
});
});
</script>
Note that replace method would work even in JQuery because Jquery is simply library of javascript :)
http://www.w3schools.com/jsref/jsref_replace.asp
replace() method is native javascript. That'll get you what you want.
You could remove spaces with using mod_rewrite. It’s quite useful way. You can also remove spaces from URLs by replacing spaces by %20, but that only helps with spaces and won't escape other characters. What you really need to do is use a URL-escaping function.

Categories