I was working on how to find a URL's domain, and thanks to my previous question, I came to this answer:
var domain = (location.host)
var arr=domain.split(".")
extension=arr[arr.length-1]
if(extension=="cnn")
alert("true");
However, I have 2 problems:
It works fine untill you come across to a site with extension co.uk.
Is there a way to count . from the start and not from the end?
For example, for the website www.cnn.com, it'd start counting from the www, and not from the com.
Okay, here's the edit to make you understand how it works.
Say, your website is "www.cnn.co.uk". If you understand array, this line would return you the array of 4 elements delimited by '.'
var arr=domain.split(".")
i.e. [www, cnn, co, uk];
Now it's really upto you what element you want out of this array. If you know the element name, and you want to retrieve cnn, you can do
`extension = arr[1];`
You can also iterate over an array to get each element.
extension = arr[0];
it will return you www.
Use this function:
function GetDomainName() {
if (location.host.split('.')[0] == 'www') {
return location.host.split('.')[1];
} else {
return location.host.split('.')[0];
}
}
Call it like this:
var domainName=GetDomainName();
But remember, this will not work in subdomains like
programmers.stackexchange.com
Demo: http://jsfiddle.net/j7VP6/
Related
I'm working up to PREV/NEXT buttons that will get the current pathname, find it in an array, and increment its index to output a redirect or link, not sure if my terminology is correct. I have it pretty much figured out, but I ran into this one question which is bugging me. There's a simple answer no doubt invisible to noobs but I don't know how to research it more than what I already did. Not a big deal to my code, but why can't I use a variable in the 2nd example; why do I have to spell out the redirect statement?
Example One: This redirect works.
<button onclick="pp();">PREV1</button>
<script>
function pp() {
var qq = window.location.pathname;
if (qq == '/F:/0-website/wwwtesting/javascript_variables_cannot.html') {
window.location.pathname = '/F:/0-website/webpage.html';
}
};
</script>
Example Two: I don't need the conditional as used in the last example, but without it the redirect doesn't work. What's the difference to JS? All I changed was to remove the conditional, and the alert works but the redirect doesn't.
<button onclick="rr();">PREV2</button>
<script>
function rr() {
var yy = window.location.pathname;
yy = '/F:/0-website/webpage.html';
};
/*alert(yy);*/
</script>
I am new on this website, and I am also new at Javascript.
What I would do is get a value from a link, eg:
http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741
I need to take this value: O=107905, if it is only one code I need to run a file (file A),
if it look like this: O=107905~107906, then I need to run a different file (file B).
What I thought is create a function with javascript where if it is (~) is missing, then will be used the file A, if there is one or more than one of (~) then the file B will start to work.
Many thanks in advance!
Well. We really do encourage you to provide your own code first before providing solutions, but this is a fairly simple problem in javascript. Here's my take on it.
The first problem you have to solve is actually getting the query string parameters in a meaningful format. Here I create an object that uses the query string keys as the object keys (IE 9+ only because of the forEach)
var tmpObject = {}
location.search.substr(1).split('&').forEach(function(item){
var o = item.split('=');
tmpObject[o.shift()] = o.shift();
});
Then it's just a matter of making sure the query string contained the target object (in this case "O") and determine if there is more than one.
if(tmpObject.hasOwnProperty('O') && tmpObject.O.split('~').length > 1) {
console.log('return multiple files');
} else {
console.log('return one file');
}
Try this
var url = "http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741";
var search = url.substring(url.indexOf("?")+1);
var map={};
search.forEach(function(val){var items=val.split("="); map[items[0]]=items[1];});
if (map["O"].indexOf("~") != -1)
{
//O value has ~ in it
}
else
{
//O has no ~ in it
}
Possible solution to get the paramter would be there : How to get the value from the GET parameters?
Once you have the parameter value, you can for sure look if you find '~' with String.prototype.indexOf.
String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.
Sorry i cant find the tutorial in google because i dont know the keyword...
var currentURL=location.href;
var str = currentURL;
if(str == "http://web.com/blabla" || str == "http://web.com/bleble"){
window.location = "http://web.com/ban";
} else {
}
How to make str == "http://web.com/blabla" || str == "http://web.com/bleble" to list ? so if i want to input some url again, i just input the url to the list. Can give me the code or link tutorial ???
Basically you'll need to place all of your URL's into an array and then iterate over the array checking each item.
var urls = ['http://web.com/','http://web.net/','http://web.org'];
var current_url = '...';
for (var i = 0; i < urls.length; i++){
if (current_url == urls[i]){
window.location = "http://web.com/ban";
break; // exit the loop since we have already found a match
}
}
The break command will terminate the loop and stop searching the array for matching URLs. Since the action you want to take needs to happen if any of the URLs match, it's enough for one to match in order to stop searching.
Lists are called arrays in javascript, and are declared using square brackets, like this: var badUrls = ["http://web.com/blabla", "http://web.com/bleble"].
To check whether the current URL appears in the array, you can use the .indexOf function of the array, which will return the first position in the array where the string you provide can be found (starting with 0 for the first element), or -1 if it doesn't exist. For example, if you have an array var arr = ["foobar", "foo", "bar", "baz"], and you do arr.indexOf("foo"), you get 1 because it's the 2nd element in the array. If instead you do arr.indexOf("fooba"), you will get -1 because none of the elements in the array are fooba exactly. In your code, you want to redirect the user if badUrls.indexOf(str) > -1. You can get more information on indexOf in the MDN Documentation.
That makes your code look like:
var currentURL=location.href;
var str = currentURL;
var badUrls = ["http://web.com/blabla", "http://web.com/bleble"]
if(badUrls.indexOf(str) > -1){
window.location = "http://web.com/ban";
} else {
}
window.location is a browser object, it you want the page to go to http://web.com/ban, you should use
window.location.href = "http://example.com/ban";
However, it looks like you are trying to prevent people from visiting pages using JavaScript. This is extremely insecure, because anyone that lists your code will see which URLs you're trying to protect and immediately request them. If they request those URLs with JavaScript disabled, or using curl, the pages will be delivered.
You should protect the pages with server side configuration. With Apache, you can use the Allow/Deny configuration or RewriteRules.
I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view.
I have two URLs the user can switch between:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
The URLs can also have some trailing querystring items, like this:
http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :)
I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position.
EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
So, you could do this:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
You can use this code:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/
Do you have a case-sensitivity issue?
Here's the issue:
I need to check for a parameter in the query. If it's been set, then I need to change it (harder part). If it hasn't been set, I need to set it (easy part)
I was so sure it would be an easy task, but it somehow ended up being a bit more complicated than I thought. Especially for those cases where there are multiple parameters, and the one I'm looking for is in the middle somewhere.
The parameter is "siteLanguage", and is always followed by =xx where xx represents any two characters, like en or es or whatever. So maybe regex is the answer (boy, do I suck at regex)
No frameworks for this one, guys, just plain ol' javascript.
I guess you've figured out how to find all the links.
The standard format of an URL is service://host/path?query
I suggest to cut away the query (just take everything after the first ?) and then split that at & (because that separates parameters).
You'll be left with an array of the form key=value. Split that into an associative array. Now you can work on that array. After you've made your modifications, you need to join the query again and set the href attribute of the link.
This would check all "a href=" throughout the document appending or adjusting the language.
checkhrefs = function(lang){
var links = document.getElementsByTagName("a");
for (var i=0;i<links.length;i++){
if (links[i].href.indexOf("siteLanguage") == -1){
links[i].href += "&siteLanguage="+lang;
} else {
links[i].href = links[i].href.replace(new RegExp("siteLanguage=[a-z][a-z]"),"siteLanguage="+lang);
}
}
}
Ended up just doing a quick hack like so:
function changeLanguage(lang) {
if (location.search.indexOf("siteLanguage") > -1) { //siteLanguage set
location.href = location.search.replace(/siteLanguage=[a-z][a-z]/, "siteLanguage="+lang);
} else if (location.search == "") {
location.href += "?siteLanguage="+lang;
} else {
location.href += "&siteLanguage="+lang;
}
}
Actually pretty happy with a 9-liner function...