Remove one parameter name and value in url using jquery - javascript

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

Related

How to modify URL Query String without reload

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()));

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/

How to access a parameter from second page?

I have a page that lists courses. When a student clicks on one of the course titles, it will use AJAX to pass the parameter (courseId) to a second page which will return the course details. How can the parameter (courseId) be accessed in the second page? If I put a value directly in the source instead of accessing the parameter, it shows the details:
var idInput = 12345;
var regNoInput = 098766;
When I tried getElementById to access the parameter, it didn't show any details:
var idInput = document.getElementById("courseId").value;
var regNoInput = document.getElementById("regNo").value;
I also tried accessing the parameter as a PHP variable, but still no details:
var idInput = "${courseId}";
var regNoInput = "${regNo}";
this is my first page script, the parameter is pass using url:
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = "<li data-mini='true' id='icon'><a href='MRegisteredClassesDetail.html?
courseId=" + [json_results.rows[key].courseId] + "&regNo=" +
[json_results.rows[key].regNo] +"' rel='external'>" +
json_results.rows[key].courseName+ "</a>" + "<a
href='http://137.57.102.146:8080/Training/MRateCourse.phone?courseId="+
[json_results.rows[key].courseId] + "&regNo=" +
[json_results.rows[key].regNo] + "' rel='external'>RATE THIS COURSE</a>
</li>" ;
listItems.append(html);
});
and this is my second page, it should read the parameter value:
var idInput = "${courseId}";
var regNoInput = "${regNo}";
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(courseId) {
html ='<h1 align=center>'+json_results.rows[courseId].courseName+'</h1>';
html +='<li>Registration Number:'+json_results.rows[courseId].regNo+'</li>';
html +='<li>Registration Date:'+json_results.rows[courseId].regDate+'</li>';
listItems.append(html);
});
if the parameter in the url,try this:
var params=window.location.search.substr(1).split("&"),
idInput=params[0].split("=")[1],
regNoInput=params[1].split("=")[1];
i declare a variable
var idInput = getParameterByName('courseId');
and define the function
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
it works well.

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

jQuery -> Change Window.href

How would I use jQuery to redirect the page to teh base page + some string?
Specifically, I need to set the window.href = current page without params + 'SomeString';
Try something like this:
window.location.href = window.location.pathname + 'SomeString';
var loc = window.location + '';
window.href = loc.replace('(\?(.+))','') + str;

Categories