Get current URL and add something in front with JavaScript - javascript

For a multi-language website, I want two buttons for the two languages that exist on the website.
The standard url would be: mydomain.com/something (this would be in german for example) The english url for this is: mydomain.com/en/something
How can I set up the buttons to get the current url/ page (in this case /something and add /en in front of it? Everything I found was to add stuff after the full domain.
Thank you very much.

check Location Obj MDM docs
console.log(document.location.origin + "/en" + document.location.pathname)

I'm not sure what your end goal is but if it involves reloading the same page with the localisation in the URL (i.e. on button click the page reloads and the page's URL is changed to mydomain.com/en/something meaning that on your next button click, the page would need to reload and its URL would need to be mydomain.com/something again) then you may need to look into RegEx and running it against the current URL to then swap out the URLs in the button so that on click you go to the correct version of the domain.
If the end goal is to only get the current URL and toggle whether the localisation appears in the URL or not then take a look at the snippet below which should hopefully help you out a bit.
For some further reading, I think these resources may be helpful for you:
RegEx: Regular expressions guide
RegEx: Regex101 - this is essentially a playground for practicing and testing your RegEx.
Location Object: MDN or W3Schools
jQuery(document).ready(function($) {
var $languageToggle = $('#language-toggle');
var origin = location.origin;
var pathname = location.pathname;
$languageToggle.on('click', function() {
var $this = $(this);
var toLanguage = $this.data('to-language');
var currentLanguage = $this.data('current-language');
var localisation = '';
/**
* This if statement will help prevent the constructedUrl variable
* from ever having a url such as https://website.com//page
* (notice the double forward slashes after .com).
*/
if (toLanguage) {
localisation = '/' + toLanguage;
}
var constructedUrl = origin + localisation + pathname;
$this.data('to-language', currentLanguage);
$this.data('current-language', toLanguage);
$('#output').text(constructedUrl);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">Click on the toggle button</div>
<button id="language-toggle" data-to-language="en" data-current-language="">
Toggle language
</button>

var myFunc = () => {
window.location.href = window.location.href + "place you text here"
}
Click the button and the page will be edited
<button onclick="myFunc()">click me</button>

Related

Display part of URL on a page (i.e. Instagram Access Token)?

What I'm trying to achieve is when a user authenticates with Instagram, and they're redirected to a page like "http://domainnamehere./instagram#access_token=27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40"
To be able to print the "27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40" string on a part of the web page, i.e.
<p>Here is your access token: ________</p>
I know how to print the whole URL using javascript, using this:
<h3 id="right">
<script type="text/javascript">
document.write(location.href);
</script>
</h3>
But how can I set it up to get only part of the URL?
Exactly what I'm trying to achieve can be seen here live http://theultralinx.com/instagram (click "setup instagram," authenticate, and then the next page shows the access token.
Thank you!
You can still look for an URI parser, but it might be obtained using basic string functions like indexOf and substring as follows:
var uri = "http://domainnamehere./instagram#access_token=27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40";
var indexOfHashVar = uri.indexOf("access_token=");
// 13 is the number of characters of "access_token="
var token = uri.substring(indexOfHashVar + 13);
console.log(token);
As #PhistucK suggested in some comment, you might get the hash part of the whole uri using window.location.hash, thus my sample may be altered in the first line with:
var uri = window.location.hash;
Never use document.write, it is discouraged.
This should work.
HTML -
<p>Here is your access token: <span id="access-token"></span></p>
JavaScript -
window.addEventListener("load", function () {
// Getting the part of the URL that starts with #.
var hash = document.location.hash,
// Storing the string for which we search in the hash.
accessTokenParameter = "access_token=";
// Setting the found value as the content of the access-token element we created
// above by taking the part of the hash (substring) that begins after the
// parameter by getting the index of the character (indexOf) with which the
// parameter name starts and adding the length of the parameter name (and =)
// in order to get past the name and start from the value.
document.getElementById("access-token").innerHTML =
hash.substring(hash.indexOf(accessTokenParameter) +
accessTokenParameter.length);
}, false);
In order to support Internet Explorer as well, you can use window.onload = or name the function and use window.attachEvent after feature detecting it.
<h3 id="right">
<script type="text/javascript">document.write(window.location.hash.split("access_token=")[1]); </script>
</h3>
you can use this
<h3 id="right"> <script type="text/javascript"> var href = location.href; href = href.replace("http://domainnamehere./instagram#access_token=",""); document.write(href); </script> </h3>
if ur link is always like the link in the question (same domain & no other variables) u can use this:
var url =location.href ;
var res = url.slice(45);
console.log(res);

How to add an variable value in between the hyperlink in javascript

I am sending an email via javascript. In mail.parameter.text property I need to send the hyperlink. In the code below I am hardcoding the url whick looks very lengthy and also I need to add the /dashboard at the end of the url. Any idea on how to shorten the url?
var parent = space.getParent();
var siteGroup = "GROUP_EMAIL_CONTRIBUTORS";
var mail = actions.create("mail");
mail.parameters.to_many = siteGroup;
mail.parameters.subject="New Site Created in Community"
mail.parameters.text=" A new site called " + document.properties.name +"is created.Click http://pc1:8080/share/page/site/"+document.properties.name+"/dashboard"+" to join the site";
//execute action against a document
mail.execute(document);
Sorry if this is a basic question I dont know javascript. This is my entire script and I am not using any html tags in between.
You can change it to something like this, for example:
mail.parameters.text="Click <a href='http://pc1:8080/share/page/site/" + document.properties.name + "/dashboard'>here</a>";
Your link will appear as "here" and nevertheless lead to the URL you specified. Is that what you mean by "shorten the url"?
Please try now.
var url = "Click http://pc1:8080/share/page/site/" + document.properties.name + "/dashboard" + " to join the site";
ail.parameters.text = url;

Get HTML Current Page name alone, followed by ".htm" from URL or Pathname using Jquery & Javascript

I have Scenario like: Below,
Following a "Menu List" having href value set to corresponding ".htm" Pages inside "Menu.html"
Click Me to got to pageOne.htm
Click Me to got to pageTwo.htm
Click Me to got to pageThree.htm
Click Me to got to pageFour.htm
Each Pages pageOne.htm, pageTwo.htm & pageThree.htm etc.. are having footer part, In footer it must be like it has to contain 3 Links with href values.
I require a solution:
If my Current page is pageOne.htm the Footer should show me shortcuts links to pageTwo.htm, pageThree.htm and pageFour.htm and wise verse depending on my current page.
So I require code to Get .htm from URL pathname.
Can we find() method of Jquery after getting the URL PATH like find(".htm") from URL.
Require just a snippet of Code to get the .htm page name alone.
Including an sample case below:
What if the Url is Like >>
"http://<10.10.21.26:9080>/myTestAoo/pageThree.htm#detailView"
I wish to get the value "pageThree.htm" alone from above url, if its the current page.
Thanks in advance
var lastPartOfUrl = document.URL.split('/').pop();
Or with regular expression:
var regexp = /([^\/]+)(.htm)/;
var match = regexp.exec(document.URL);
console.log(match[0]); // pageThree.htm
console.log(match[1]); // pageThree
console.log(match[2]); // .htm
The following will give you the current URL, which you can tidy up using replace():
window.location.href
you may try this code:
var a = window.location.href;
var fileName = a.substring(a.lastIndexOf('/')+1);
alert(fileName);
use window.location.pathname; will returns the full path
try following function
function getFileName(){
var url = window.location.pathname;
var path=url.split("/");
var filname=path[path.length-1];
return filname;
}

Get current URL and modify subdirectory and then go to URL with Javascript

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders:
/en/
/chi/
What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.
But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
but it doesn't explain how to modify and go to the new link.
You help will be greatly appreciated!!
To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.
Here's a script that does this with JavaScript if that's what you decide you'd like to do.
<!DOCTYPE html>
<body>
Content before the link.
<script>
(function () {
// this assumes you're on the en version and want to switch to chi
var holder = document.createElement("div");
var url = window.location.href.replace("/en/", "/chi/");
var link = document.createElement("a");
link.innerText = "Chewa"; // or whatever the link should be
link.href = url;
holder.appendChild(link);
document.write(holder.innerHTML);
})();
</script>
Content after the link.
</body>
If you simply want to take the full URL and replace /en/ with /chi/ or vise-versa, use the code below.
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
Or, a bit more concise (un-commented version)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
Note: In JS, when you modify window.location.href, the new URL is automatically loaded.
Here's a working fiddle for you to play with.
It looks like you need to change the window.location.pathname. For example:
// assuming the url `http://www.example.org/en/foo/bar/page.html`
var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");
See:
https://developer.mozilla.org/en/DOM/window.location

Make a link non-secure

I have a JavaScript link that is as follows:
<a href="#" onclick="window.open('TrackPackage.asp?track=235&ship=OTHER&ShippingMethod=1', '', 'location=1,menubar=1,scrollbars=1,status=1,resizable=1,width=635,height=460'); return false;">
<span class="PageText_L288n">TRACK YOUR PACKAGE</span>
</a>
However, it is being linked from a secure page, so it becomes a secure page. Unfortunately this creates a problem for me since a unsecured form is automatically submitted when they arrive at the page. They get prompted: this form is being submitted insecurely. There isn't any sensitive data on those pages so I really don't need the page to be secured in the first place. Is there an attribute, either in HTML or JavaScript that could make a link not secure. I cannot really modify the link itself because it's a dynamic link.
However, I do believe some jQuery can add http://www.example.com/ before the TrackPackage.asp. I guess that would be acceptable, but I'd prefer some kind of attribute that will just make the link non secure. Thanks
You might try to override native function. But in some browsers that may not work (did not find such browser, so assume that it works in all, at least major, browsers :) ):
var windowOpen = window.open;
window.open = function(url, name, settings) {
var url = 'http://www.example.com/' + url;
alert("New url = " + url);
windowOpen(url, name, settings);
}
If you want to do it for a selected class of the links then you can do it like this (the idea of the onclick attribute modification as a text string is not the best one)
<script>
var windowOpen = window.open, clicked = false;
window.open = function(url, name, settings) {
if (clicked) var url = 'http://www.example.com/' + url;
alert("New url = " + url);
windowOpen(url, name, settings);
}
$(document).ready(function(){
$('span.packagetracklink').click(function(){
clicked = true;
setTimeout(function(){clicked = false;}, 200);
});
});
</script>
<a href="#" onclick="window.open('some_url', '', ''); return false;">
<span class="packagetracklink">TRACK YOUR PACKAGE</span>
</a><br>
<a href="#" onclick="window.open('some_url', '', ''); return false;">
<span class="another_class">TRACK YOUR PACKAGE</span>
</a>
If you receive dynamically the .asp page before using it in the window.open you could just make a String replace to substitute the "https" for an "http" protocol in the URL or in case there's any protocol, add the "http" at the beginning of if.
I haven't tried this since I don't have an https page to play with but I think it can work.
You need to somehow be able to get the instance of that A tag first. It doesn't have an ID or CLASS, so you're on your own there (unless you paste parent element code and siblings code, at least snippets.
var link = $("a"); // I don't have enough info to tell you how to precisely get this instance
var originalOnClick = link.attr("onclick");
var part1 = "window.open('"; // this is always the same, right?
var part2 = originalOnClick.substr(part1.length); // the remainder, beginning with TrackPackage.asp
var newOnClick = part1 + "http://www.example.com/" + part2;
link.attr("onclick", newOnClick);
There are other ways to inject a string constant into existing string, but this should work - if I understood you well enough.

Categories

Resources