Tidying Javascript, Catching and manipulating URLs - javascript

Im very new to Javascript and have created the following code through lots of googling and finally have it doing what it needs to however, I am sure i will have done it the messy way.
I want it to get the current URL, remove the domain, then replace any _ with a space and finally place that value in a div.
$(document).ready(function() {
//pure javascript
//var URLname = window.location;
var URLname = "www.blahblah.com/John_Smith";
var CutURL = URLname.substring(URLname.lastIndexOf("/"));
var result = CutURL.substring(1);
var result = result.replace(/_/g, ' ');
document.getElementById("URLHolder").innerHTML = result;
});
Have i done this in the simplest form already? I just think passing the variable though could be done in one go but I'm unsure 100% how.
I will have a further play as I wait for advice.
Many thanks.

It might be easier to use window.location.pathname which will return just the bit after the domain.
// with url: "www.blahblah.com/John_Smith";
var cutURL = window.location.pathname; // John_Smith
var result = cutURL.replace(/_/g, ' ');

Related

Bookmarlet: Take number from end of URL and put it in a new URL?

I want to create a bookmarklet that will take something like this;
http://www.site1.com/some/random/path/12345
And change it into this, then reload the page;
http://www.site1.com/new/path12345?value=true
Unfortunately I haven't tried much, because I know absolutely nothing about Javascript. I tried to copy a bit of code that does a search and replace on the URL and then tried to add the functions for appending a string, but that didn't work because I had no idea what I was doing or even the proper syntax I was supposed to use. Javascript seems to have about a dozen different ways to alter the current URL and I have no idea when to use each one.
try this,
var urlArray = [];
var myURL= http://www.site1.com/some/random/path/12345;
urlArray = myURL.split('/');
var newURL = "http://www.site1.com/new/"+urlArray[urlArray.length-2]+""+urlArray[urlArray.length-1] +""+"?value=true";
var myPageLink = document.createElement('a');
myPageLink .setAttribute('target', '_blank');
myPageLink .href = newURL;
document.body.appendChild(myPageLink );
myPageLink .click();

Retrieve URL Parameters Sent Through JQuery .load()

I am not sure if what I'm trying to do is possible or if I'm going about this the right way. In some circumstances I want them to have a GET parameter as part of the URL. I want the receiving page to be able to differentiate whether the sending load has a parameter or not and adjust accordingly.
Here is what I have that is sending the load:
$(document).ready(function () {
$("a").click(function () {
$("div.pageContent").html('');
$("div.pageContent").load($(this).attr('href'));
return false;
});
});
In this case, the load could have "example.php" or "example.php?key=value". In looking around (primarily on this site), I've found things that seem to be close, but don't quite get there. In the page that is getting loaded (example.php), I have the following:
function $_GET(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
$(document).ready(function () {
var URL = "example2.php";
if ($_GET('key'))
{
URL = "example2.php?key=" + $_GET('key');
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
If the sending source includes a query string, I want to add that to the URL and load it in a div that is unique to this page, otherwise I want to just load it as is without the query string. The big issue I'm running into (I believe) is since this is coming from an AJAX call, the "window.location.href" is not what was sent from the JQuery but rather the URL of the root page which never changes. Is there a way to be able to know what the full URL is that was sent from the load() in the first page by the second one?
Thank you in advance for your help.
I realized that the GET parameters were getting passed as I could access them through php without issue. I didn't know that I could insert php code into a javascript block but once I tried it, all worked out. My new code looks like this:
$(document).ready(function () {
var URL = "example2.php";
var myValue = "<?php echo $_GET['key']; ?>";
if (myValue !== "")
{
URL = "example2.php?key=" + myValue;
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
I was able to get rid of the GET function out of javascript entirely. I probably made this much more difficult from the start but hopefully it can help someone else in the future.

jQuery hiding content based on url

hi all i am trying to hide content for a ppc campaign, so if they come from the link they will have something like "/?utm_source=google" on the url
Ive got the following but it only works for that exact url
var url = "http://mysite.com/?utm_source=google";
if (location.href==url){
$('div').hide();
}
Ideally it needs to work for multiple pages i.e. http://mysite.com/page-one/?utm_source=google
Just wondering if anyone knows a way around this?
use a regexp match:
if (location.href.match(/utm\_source\=google/ig)){
$('div').hide();
}
var option = 'coke';
var url = window.location.href;
option = url.match(/option=(.*)/)[1];
showDiv(option);
});
function showDiv(option) {
$('.boxes').hide();
$('#' + option).show();
}
Read the Contents

Javascript random redirect

so my situation is as follows:
I wrote a submission system in php that writes to a textfile rather than a database, the idea of the system is people submit their url to the textfile and then when that script is called on a page, it redirects to a random address out of the textfile; the problem is, I don't know how to make javascript read from the text file and then pick a line to redirect to.
Actually, just to clarify, I know how to make javascript read from the text file; but I have NO idea how id write a function to pick a url from the file and forward to it.
Seeing as I hit this road block a couple of days ago, the only way I have been handling submissions is checking the text file every 12 hours for new submissions and then manually adding them to this code:
setTimeout(function() {
var howMany = 38;
var page = new Array(howMany+1);
page[0]="http://gproxy.nl/";
page[1]="http://homeproxy.me/";
page[2]="http://proxyturbo.com/";
page[3]="http://www.lblocker.info/";
page[4]="http://goprivate.eu/";
page[5]="http://jsproxy.com/";
page[6]="http://openthis.eu/";
page[7]="http://proxy4home.info/";
page[8]="http://dedicatedipaddress.net/";
page[9]="https://www.4everproxy.com/";
page[10]="http://www.surfsearch.info/";
page[11]="http://www.leaveproxy.com/";
page[12]="http://proxyecole.fr/";
page[13]="http://newipnow.com/";
page[14]="http://www.hiddenmode.info/";
page[15]="https://europrox.org/";
page[16]="https://www.4everproxy.com/";
page[17]="https://goingthere.org/";
page[18]="http://xuxor.com/";
page[19]="http://033b.com/";
page[20]="http://thewebtunnel.com/";
page[21]="http://prox.phanteye.com/";
page[22]="http://www.hiddenall.info/";
page[23]="http://www.5966.info/";
page[24]="http://hideyoself.com/";
page[25]="http://prox.phanteye.com/";
page[26]="http://freevideoproxy.com/";
page[27]="http://thewebtunnel.com/";
page[28]="http://openthis.eu/";
page[29]="https://europrox.org/";
page[30]="http://xuxor.com/";
page[31]="https://incloak.com/";
page[32]="http://www.leaveproxy.com/";
page[33]="http://www.openunblocker.com/";
page[34]="http://post48.com";
page[35]="http://post48.com";
page[36]="http://inteproxy.com";
page[37]="http://208.73.23.59";
page[38]="http://hidemetoday.com/";
function rndnumber(){
var randscript = -1;
while (randscript < 0 || randscript > howMany || isNaN(randscript)){
randscript = parseInt(Math.random()*(howMany+1));
}
return randscript;
}
quo = rndnumber();
quox = page[quo];
window.location=(quox);
}, 1500);
I would be very grateful if someone would help me write the script or tell me what kind of function I should be googling to look up, googling "How to make javascript read from a textfile and redirect" doesn't really turn up much ; (
Many thanks!
If I understand correctly, first, you'll need a regex to find the URLs in the file. I would refer to this SO post for that: regular expression for url
Once you have that, you can go to any URL with window.location.href = 'http://google.com';
So, you'll do something like this...
var urlPattern = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/g;
var urls = data.match(urlPattern);
if (urls) {
window.location.href = urls[7];
}
Is that what you're looking for?
Or you can use a more simple regex like var urlPat = /https?:\/\/[^'"]+/g
Remember to use the /g flag with your regex to get all occurrences of the urls.

Using JavaScript to perform a GET request without AJAX

Out of curiosity, I'm wondering about the best (easiest, fastest, shortest, etc; make your pick) way to perform a GET request in JavaScript without using AJAX or any external libraries.
It must work cross-browser and it's not allowed to distort the hosting web page visually or affect it's functionality in any way.
I don't care about headers in the request, just the url-part. I also don't care about the result of the request. I just want the server to do something as a side effect when it receives this request, so firing it is all that matters. If your solution requires the servers to return something in particular, that's ok as well.
I'll post my own suggestion as a possible answer, but I would love it if someone could find a better way!
Have you tried using an Image object? Something like:
var req = new Image();
req.onload = function() {
// Probably not required if you're only interested in
// making the request and don't need a callback function
}
req.src = 'http://example.com/foo/bar';
function GET(url) {
var head = document.getElementsByTagName('head')[0];
var n = document.createElement('script');
n.src = url;
n.type = 'text/javascript';
n.onload = function() { // this is not really mandatory, but removes the tag when finished.
head.removeChild(n);
};
head.appendChild(n);
}
I would go with Pekka idea and use hidden iframe, the advantage is that no further parsing will be done: for image, the browser will try to parse the result as image, for dynamically creating script tag the browser will try to parse the results as JavaScript code.. iframe is "hit and run", the browser doesn't care what's in there.
Changing your own solution a bit:
function GET(url) {
var oFrame = document.getElementById("MyAjaxFrame");
if (!oFrame) {
oFrame = document.createElement("iframe");
oFrame.style.display = "none";
oFrame.id = "MyAjaxFrame";
document.body.appendChild(oFrame);
}
oFrame.src = url;
}

Categories