I'm passing URL parameters from the current link to another link but the new parameters are added as "&?firstName=test&lastName=testing" and should be just "&firstName=test&lastName=testing"
<script>
$('#redirectButton').click(function() {
const url = window.location.href;
const params = url.split('/');
const parameter = params[params.length-1];
const page2 = "www.newwebsite.com/page?existingParam=true" +parameter;
window.location.href = page2
});
</script>
If your URL is something like www.mywebsite.com/blah/blahblah/test?a=1&b=2, then the last item of the split list would be test?a=1&b=2. Blindly adding this to something like www.myotherwebsite.com/blah/test?existing=true would give www.myotherwebsite.com/blah/test?existing=truetest?a=1&b=2. However, you only want a=1&b=2 to be added (and of course, an & before all that). Thus, we can split by ? and add & plus the last part.
let url = 'www.mywebsite.com/blah/blahblah/test?a=1&b=2';
let redirectURL = 'www.myotherwebsite.com/blah/test?existing=true';
let splitL = url.split('/');
console.log('Redirecting to...');
console.log(redirectURL + '&' + splitL[splitL.length - 1].split('?')[1]);
This is assuming that your URL is not like www.someotherwebsite.com/test?a=1&text=Hello,%20how%20are%20you%20doing? with a question mark in the parameters. If it is, then you should use indexOf to find the index of the first question mark in splitL[splitL.length - 1], and use a slice from that index (plus 1) instead.
i use the code below to format some links. Where it can add either a suffix or a prefix to the link. But i have been researching how to remove part of the link.
Example, this link below.
https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html?cgid=Clothing_Jeans_Straight_Boyfriend#promo_id=210802_Jeans&promo_name=BoyfriendStraight_BoyfriendStraight&promo_creative=2107_FG_Denim_Boyfriend_Straight_277x702&promo_position=Jeans_Slide3&start=1
It has superfluous data, everything after
https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html
Isn't needed, how can i remove everything past that point when formatting the links, before adding the suffix or prefix. Thanks in advance for any help!
$("#btnGenerateLinks").on("click", function() {
var valNeed = $("#strngtime").val();
// if (valNeed.trim().length) { // For filter blank string
$('input[name="linktype1"]').each(function() {
$(this).val($(this).data("link") + valNeed);
});
$('input[name="linktype2"]').each(function() {
$(this).val(valNeed + $(this).data("link"));
});
// }
});
Update - Yes all query parameters
Update - Going with a simple split for now
var myArr = valNeed.split("?")[0];
you can use the URL constructor API
let url = "https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html?cgid=Clothing_Jeans_Straight_Boyfriend#promo_id=210802_Jeans&promo_name=BoyfriendStraight_BoyfriendStraight&promo_creative=2107_FG_Denim_Boyfriend_Straight_277x702&promo_position=Jeans_Slide3&start=1"
let instance = new URL(url);
let cleanURL = instance.origin + instance.pathname;
console.log(cleanURL);
// https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html
I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}
I have tried googling this but can't find what I'm looking for. I have a url that has a number in it. I want to be able to take the number that is there and depending on what number is there then interject a name back into the url. For example:
Let's say the url is: www.example.com/video15637
Can I take that number and then do something like:
var nameVariable;
if(video15637){
nameVariable = video15637;
}
if(video26597){
nameVariable = video26597;
}
if(video18737){
nameVariable = video18737;
}
then, somehow interject the namevariable back into the url that is displayed?
You can try with:
var a = document.createElement('a');
a.href = 'http://www.example.com/video15637';
var nameVariable = a.pathname.substr(1); // video15637
You can simple use .split() or combination of .substr() and .lastIndexOf()
var url = 'www.example.com/video15637';
var video = url.split('/')[1];
alert(video)
OR
var url2 = 'http://www.example.com/video15637';
var video2 = url.substr(url.lastIndexOf('/') + 1);
alert(video2)
Combined DEMO
/**
* Political Animals
* contentscript.js is loaded on each page(s) listed in manifest.json
* This plugin replaces all the images on the website of news sites with pictures of
* animals in suits, as a commentary on what the news has become. Made for Web 2
* November 20, 2013
*/
//Random Image array
var arrayImg = ['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg','http://ny-image0.etsy.com/il_fullxfull.85564656.jpg','http://afraidofmice.com/blog/wp-content/uploads/2011/08/berkleyill.jpg','http://elizabethmarshallgalleryblog.files.wordpress.com/2011/05/etsy-panda-for-blog1.jpg','http://moesewco.typepad.com/.a/6a00e5500684b488330120a5c7cf3a970c-300wi','http://ih3.redbubble.net/image.13276877.5059/flat,800x800,070,f.u1.jpg','http://www.tildeshop.com/blog/wp-content/uploads/2012/09/SeaLionFemale-21.jpg'];
//redirect
var acceptedWebsites =['www.cnn.com', 'www.nytimes.com', 'www.latimes.com', 'www.washingtonpost.com', 'www.nbcnews.com', 'www.foxnews.com'];
var currentUrl = document.location.href;
var referrer = currentUrl.match(/:\/\/(.[^/]+)/)[1];
//Making sure the code does what I want it to. As long as the link shows a number greater than -1, then the site extension is working
console.log(referrer);
console.log(acceptedWebsites.indexOf(referrer));
//var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
//document.location.href = url;
// image source goes through the following script function
$('img').each(function(){
// creating the randomizing
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
//Takes the current array and applies the source with the random function
$(this).attr('src', random);
//removing the stretch
var theWidth = $(this).width();
var theHeight = $(this).height();
if (theWidth < theHeight) {
$(this).height(150);
}
else {
$(this).width(150);
}
});
//alert ("Go to any of the follow websites: fox.com, nbc.com, nytimes.com, latimes.com, or cnn.com");
I have this array in javascript. I want to have it so that the user is automatically redirected to one of the links from the array, possibly randomly. I don't know if I can do this in javascript. I am using this for a chrome extension, so I don't know if I can use php.
These are fantastic answers, except they constantly redirect. I want it so that they are just redirected to one from the array once, not constantly redirect.
**Edit 2: I added my whole code because something is causing there to be a constant redirect instead of only once.
**Edit 3: I updated my code. The console.log proves that my new variables work and do ==-1. How can I use them to redirect?
Get a random URL from the array, and redirect ?
if ( acceptedWebsites.indexOf(document.location.href) == -1 ) {
var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
document.location.href = url;
}
Try the following:
var acceptedWebsites =['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
var number = Math.floor(Math.random() * acceptedWebsites.length);
number will generate a random number between 1 and the number of entries in your acceptedwebsites array.
window.location = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
The basic jist of the logic would be...
var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
var randomLink = Math.floor(Math.random() * acceptedWebsites.length);
window.location = acceptedWebsites[randomLink];
// Get random site
var randomSite = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
// redirect to selected site
window.location = randomSite;
Generate a "random" key and use window.location.href to redirect the user. Others have posted the same approach, though with less explanation. I'm giving my best to let you actually understand what happens here.
Note that most of this code is comments. It looks longer than it actually is.
var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
// This function returns a random key for an array
function randomKey(arr) {
// Math.random() returns a number between 0 and 0.99999...
// If you multiply this value with the length of an array, you get a
// random floating point number between 0 and that length.
// Use Math.floor() to round it down to the next integer
return Math.floor(Math.random() * arr.length);
}
// Select a random website from the array
var key = randomKey(acceptedWebsites);
var newLocation = acceptedWebsites[key];
// Redirect the user
window.location.href = newLocation;
Try this solution:
var size = acceptedWebsites.length;
var x = Math.floor((Math.random()* size)+1);
Now use loop for value x-1 like
var location = acceptedWebsites[x-1];
window.location.href = location;
If we run this in loop ,we will get different value of x every time between 0-size of array and then we can use that random value to randomly redirect.
window.location doesn't work since content scripts are unprivileged. Further more, window.location.href returns the current location, but it is not a method so you cannot overwrite it.
you'll need to:
Send redirect url from a content script to a background page:
var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
chrome.extension.sendRequest({redirect: url });
In a background page update tab's url which would cause redirect:
chrome.extension.onRequest.addListener(function(request, sender) {
chrome.tabs.update(sender.tab.id, {url: request.redirect});
});