ASP MVC JavaScript ActionLink multiple replace? - javascript

I want to build a Url.Action link and pass parameters and I found an example here on stackoverflow that shows how to replace the value:
var url = "#Url.Action("Export", "UserCalendar",new { from =
"_date", to="_to", groupId="_groupId" })".replace("_date",
_pdfExportStartDate);
How do I also replace _to and _groupId ? I tried
url = url.replace("_to",_pdfExportEndDate)
after the first replace call and although it makes the correct URL string the value (_to) is never passed to the controller.

You can simply add the querystring params to the base url (the one without any route values) as needed.
var _pdfExportStartDate = "11/11/2013";
var _toDate = "11/11/2013";
var baseUrl = "#Url.Action("Export", "UserCalendar")";
url = baseUrl +"?from = "+_pdfExportStartDate +"&to= "+ _toDate;

Related

Getting out a product ID from URL - JavaScript

I'm trying to catch only a product ID from a URL. The ID is broke into 2 pieces:
https://www.example.org/category/first_part_of_ID-some_text-second_part_of_id
I was stuck with this function
var ft = "ft_";
var pod = "_";
var pageUrl = window.location.href;
var pageUrl1 = pageUrl.split("-")[1];
var pageUrl2 = pageUrl.replace("/","");
return pageUrl2;
}
Can anyone please help me clearing out everything except for the numbers? I tried with 2 different functions and putting it together, but it also didn't work.
This answer assumes the id you are trying to extract will always follow /category/ in the URL as well as that the first and second parts of the id always be located between the -some_text- part of the url
const url = window.location.href;
const urlAfterCategory = url.split('/')[4];
const id = `${urlAfterCategory.split('-')[0]}${urlAfterCategory.split('-')[2]}`
console.log(id); // Your id

print value of URL Parameters hash js

I am trying to get the parameters from a URL using js i have a url :
http://www.example.com?i=aGVsbG8gd29ybGQ=
i want to decode base64 ?i value and print decode value here using javascript
<input id="i" type="hidden" value="decode value" />
Try this :
var parameterValue = atob(window.location.search.match(/(\?|&)i\=([^&]*)/)[2])
console.log(parameterValue);//"hello world"
document.getElementById('i').value=parameterValue;
This might help too : https://stackoverflow.com/a/26995016/957026
you could use the window.location API https://developer.mozilla.org/en-US/docs/Web/API/Location
console.log(window.location.search);
You will get as a response ?i=some-value
Yes you can get the value from url and and decode it.
Use below code
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
let x = atob(getUrlVars().i);
console.log(x); // hello world
document.getElementById('i').value = x;
To parse URL strings, modern browsers provide a class called URLSearchParams and this is the easiest way to extract URL values.
You can create an instance of that class by passing it the search property of window.location (after removing the initial "?"), and then it will do all the work for you:
// eg. https://example.com/?name=Jonathan&age=18&i=aGVsbG8gd29ybGQ=
const params = new URLSearchParams(window.location.search.substring(1)); // remove "?"
const name = params.get("name"); // is the string "Jonathan"
const age = parseFloat(params.get("age")); // is the number 18
const i = whateverDecodingFunctionYouUse(params.get("i")); // decoded aGVsbG8gd29ybGQ
See: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/

Replace parameter in a url string using JavaScript inside Google Tag Manager

I am trying to replace a parameter in a url with another using GTM. In the link below, I want to replace amazon affiliate tag ID "bestelectricridesweight-20" with "electricridessg-20"
https://www.amazon.com/SWAGTRON-T6-Off-Road-Hoverboard-Certified/dp/B01NH2WD3Z?psc=1&SubscriptionId=AKIAIWWM3HVERXCJ5HLA&tag=bestelectricridesweight-20
I tried this javascript code but it's not working:
(function () {
var linkss = document.querySelectorAll('a[href*="amazon.com"]') //change amazon.com to any domain you want to target
var searchString = "bestelectricridesweight-20" //the string to be searched for
var replacementString = "electricridessg-20" //the replacement for the searched string
linkss.forEach(function(linkd){
var original = linkd.getAttribute("href");
var replace = original.replace(searchString,replacementString)
linkd.setAttribute("href",replace)
You can use use URL API and searchParams.set method to change the value of tag searchparameter
let parsed = new URL("https://www.amazon.com/SWAGTRON-T6-Off-Road-Hoverboard-Certified/dp/B01NH2WD3Z?psc=1&SubscriptionId=AKIAIWWM3HVERXCJ5HLA&tag=bestelectricridesweight-20")
parsed.searchParams.set('tag', 'electricridessg-20')
console.log(parsed.toString())
var href = new URL(linkd.getAttribute("href"));
href.searchParams.set("tag", replacementString);
linkd.setAttribute("href", href.toString());

Modifying HTTP GET Request via Select Menu Change - Update Parameter

I have a search results page in a PHP site that returns a list of results using pagination. The URL looks like this:
findProducts.php?action=searchAssets&orderNumber=xxxx&productName=zzz&skip=20
I have a select menu that allows the user to modify/filter the search results which triggers a script like this:
$(document).ready(function() {
$('#productType').change(function() {
window.location.href = window.location.href + '&productType=' + $(this).val();
});
});
This is working well except for one thing - I need to reset the 'skip' parameter to 0 for the new filter search as the pagination values from the previous search won't be valid or applicable. Is there a way I can change:
skip=20
to:
skip=0
as part of this script?
You could do a RegExp replace on the URL:
window.location.href = window.location.href.replace(/((?:\?|&)skip)=\d+/, '$1=0') + '...';
(untested)
Note that you should do the same with the productType because otherwise you'll add it again and again.
Better solution would possibly be to have a base URL and then add all necessary parameters instead of doing search and replace...
You can get the query from the URL by splitting the URL using ?
This will give you the base url in the first index and the query in the second.
You can then get the query parameters by splitting the query using &.
You can loop through all of the parameters checking if it is the skip parameter. If the parameter is the skip parameter push your new value to an output array. Otherwise push the unchanged parameter to an output array.
You can then use join to join all of your output elements using & to reconstruct the query and return your original base url with your new query string.
<script>
function fixQuery(qstr) {
var parts = qstr.split('?');
var query = parts[1];
var a= query.split("&");
var out=[];
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
if(decodeURIComponent(b[0])=="skip")
{
out.push("skip=0")
}
else {
out.push(a[i]);
}
}
return parts[0] + '?' + out.join("&");
}
var result= fixQuery("http://example.com/findProducts.php?param1=test+thing&param2=hello&skip=10");
console.log(result)
//http://example.com/findProducts.php??param1=test+thing&param2=hello&skip=0
</script>

Search URL parameters with Angular JS

Say I have a URL like this:
www.mysite.com?account=23&token=asdu756sdg65sdf
Now, I need to access those URL parameters individually using Angular JS.
I've tried using location.search inside my controller:
console.log(location.search);
Which nicely returns the full query string:
?account=23&token=asdu756sdg65sdf
But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?
I've also tried:
console.log($location.search());
Which seems to return an empty object.
Try with
var account = ($location.search()).account;
but the url should be like /#!/?account=1
have your tried using it as a function instead?
$location.search();
pure js way:
var getParamFromURL = function(_url) {
var url = _url;
var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
var _paraObj = {};
for (i = 0; p = _paraString[i]; i++) {
_paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
}
return _paraObj;
}
via angular js:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
Great. #Cooper is right.

Categories

Resources