I have been digging in some javascript api's lately and I found the following line:
get_url_info: function($db_link) {
var ldst_href;
if ($db_link.data('ldst-href')) {
ldst_href = $db_link.data('ldst-href');
}
else {
ldst_href = $db_link.attr('href');
}
var matchs = ldst_href.match(/^http:\/\/([^\.]+)\..*playguide\/db\/(.*?)\/?(#.+)?$/);
var subdomain = matchs[1];
var path = matchs[2];
if (!eorzeadb.dynamic_tooltip && eorzeadb.versions.data) {
url = eorzeadb.cdn_prefix + 'pc/tooltip/' + eorzeadb.versions.data +
'/' + subdomain + '/' + path + '.js';
}
else {
url = ldst_href + '/jsonp/';
}
return {
'url': url,
'data_key': subdomain + '/' + path
};
},
This result is supposed the return an array which I assume is contained in the link. I'm having a hard time decrypting the link tho.
Does anybody have any experience with these kinds of links or a way that I could start out?
http://regexr.com/
Here you can understand all the parts of the regex. Basically, is looking for a pattern like this:
http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)
The result will be an array with the original link, followed by the domain, the first optional argument, and the hashtag, something like this
["http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)", "(blablah)", "(OPTIONAL)(optional/)", "#(probably some id)"]
It will then use that information to build a different link
Related
I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en
But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:
http://localhost/modules/product/product.php?id=1&lang=en
How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?
Try checking to see if querystring params already exist in the URL.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
Update: Account for Subsequent Lang Changes
This assumes that the lang value will always be two characters.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there.
So you could just add an if statement, looking if there is .php writen at the end.
Not a very pretty solution but you are alreaady adding strings together so it doesn't matter
You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.
const params = new URLSearchParams(window.location.search);
const paramsObj = Array.from(params.keys()).reduce(
(acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);
This should fix it:
var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;
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 am copying a function that will take a youtube/vimeo url and return what site the video came from (vimeo/yt) as well as the video id.
Here's what I have so far: http://jsfiddle.net/csjwf/181/
<strong>Result:</strong>
<div id="result"></div>
function parseVideoURL(url) {
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).+$/);
return {
provider : RegExp.$1,
id : RegExp.$1 == 'vimeo' ? RegExp.$2 : RegExp.$3
}
}
var result = document.getElementById("result");
var video = parseVideoURL("http://www.youtube.com/watch?v=PQLnmdOthmA&feature=feedrec_grec_index");
result.innerHTML = "Provider: " + video.provider + "<br>ID: " + video.id;
var video = parseVideoURL("http://vimeo.com/22080133");
result.innerHTML += "<br>--<br>Provider: " + video.provider + "<br>ID: " + video.id;
Output:
Result:
Provider: youtube
ID: PQLnmdOthmA
--
Provider: vimeo
ID: 2208013
However, notice how for vimeo vids, if the url ends in the ID, the last number is always cut off. If you add a slash to the end of the vimeo url the id is pulled fully.
The .+$ at the end is requiring at least one character after the last digit that is captured as a string of digits. That will chop one digit off what is captured. Is there a reason you have that there?
You can change the last + to a * like this:
/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).*$/
or even better, get rid of the end part entirely since it doesn't look like it's needed:
/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/
Here's a bit safer way to write your function that allows for any order of the query parameters in the youtube URL and doesn't put stuff into the regex that doesn't need to be there. The code is longer, but it's much more robust and would be much easier to add more providers:
function parseVideoURL(url) {
function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}
var retVal = {};
var matches;
if (url.indexOf("youtube.com/watch") != -1) {
retVal.provider = "youtube";
retVal.id = getParm(url, "v");
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
}
return(retVal);
}
Working version here: http://jsfiddle.net/jfriend00/N2hPj/
Here is an updated version that also works with youtu.be and youtube.com/embed urls using #jfriend00's code and some code found here: JavaScript REGEX: How do I get the YouTube video id from a URL?.
EDIT: Updated my answer (and the fiddle) with a function that actually works. :-)
function parseVideoURL(url) {
function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}
var retVal = {};
var matches;
var success = false;
if ( url.match('http(s)?://(www.)?youtube|youtu\.be') ) {
if (url.match('embed')) { retVal.id = url.split(/embed\//)[1].split('"')[0]; }
else { retVal.id = url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0]; }
retVal.provider = "youtube";
var videoUrl = 'https://www.youtube.com/embed/' + retVal.id + '?rel=0';
success = true;
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
var videoUrl = 'http://player.vimeo.com/video/' + retVal.id;
success = true;
}
if (success) {
return retVal;
}
else { alert("No valid media id detected"); }
}
And a working jsfiddle: http://jsfiddle.net/9n8Nn/3/
Out of the two stackexchange answers, this is the code that worked best for me in the end.
To simplify your regex I would use haystack.indexOf(needle) to determine if the url is vimeo or youtube and then apply site specific regex. Much easier, and later you can add video sites without overly complicating the regex.
Last number gets cut off because you're using ".+" at the end, which means "one or more of any character". Replace the + with a *, meaning "zero or more".
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+).+|(\d+))$/);
Remove the last . and the end matching
url.match(/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/);
I have tried some tips I was given on regards URL encoding but I have no success so far. First, I was given this format,
var url = "http://www.polyvore.com/cgi/add?title="
+ encodeURIComponent(%%GLOBAL_ProductName%%)
+ "&url=" + encodeURIComponent("http://lilaboutique.co.uk/products/"
+ encodeURIComponent(%%GLOBAL_ProductName%%)
+ "&imgurl=" + encodeURIComponent(%%GLOBAL_ThumbImageURL%%)
+ "&desc=" + encodeURIComponent(%%GLOBAL_ProductDesc%%)
+ "&price=" + encodeURIComponent(%%GLOBAL_ProductPrice%%));
which never got to be passed to the href dunno for what reason. Then I played with it some more,
var url = "http://www.polyvore.com/cgi/add?title=encodeURIComponent(%%GLOBAL_ProductName%%)&url=http://lilaboutique.co.uk/products/encodeURIComponent(%%GLOBAL_ProductName%%)&imgurl=encodeURIComponent(%%GLOBAL_ThumbImageURL%%)&desc=encodeURIComponent(%%GLOBAL_ProductDesc%%)&price=encodeURIComponent(%%GLOBAL_ProductPrice%%)";
this time the URL was passed but the values were mixed between the appropriate and other fields displaying the encoding function itself.
Any help clarifying my mistakes is greatly appreciated. I would like to encode just price and description, seems to be the fields giving problems.
A regular link does render without problems
var url = "www.google.com";
var myAnchor = document.getElementById('myAnchor');
myAnchor.href = url;
Thanks for any help
Nicer, cleaner way of doing this:
var toEncode = {
title: '%%GLOBAL_ProductName%%',
url: 'http://lilaboutique.co.uk/products/%%GLOBAL_ProductName%%',
imgurl: '%%GLOBAL_ThumbImageURL%%',
desc: '%%GLOBAL_ProductDesc%%',
price: '%%GLOBAL_ProductPrice%%'
};
var index, queryString = '';
for (index in toEncode)
{
queryString += index + '=' + encodeURIComponent(toEncode[index]) + '&';
}
var url = "http://www.polyvore.com/cgi/add?" + queryString;
jQuery's $.param(obj) is very nice.
In general though I would take a similar approach if you wanted to roll your own. Make a function that accepts an Object, and returns a query string. Then in your server template, you have:
var urlData = {
url: "http://lilaboutique.co.uk/products/",
imgurl: "%%GLOBAL_ThumbImageURL%%",
desc: "%%GLOBAL_ProductDesc%%"
// etc...
}
var url = "http://www.polyvore.com/cgi/add?" + $.param(urlData);
Or whatever conversion function you want to use.
I am having the URL http://somesubdomain.domain.com (subdomains may vary, domain is always the same). Need to take subdomain and reload the page with something like domain.com/some/path/here/somesubdomain using greasemonkey (or open a new window with URL domain.com/some/path/here/somesubdomain, whatever).
var full = window.location.host
//window.location.host is subdomain.domain.com
var parts = full.split('.')
var sub = parts[0]
var domain = parts[1]
var type = parts[2]
//sub is 'subdomain', 'domain', type is 'com'
var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain
window.open(newUrl);
The answer provided by Derek will work in the most common cases, but will not work for "xxx.xxx" sub domains, or "host.co.uk". (also, using window.location.host, will also retrieve the port number, which is not treated : http://www.w3schools.com/jsref/prop_loc_host.asp)
To be honest I do not see a perfect solution for this problem.
Personally, I've created a method for host name splitting which I use very often because it covers a larger number of host names.
This method splits the hostname into {domain: "", type: "", subdomain: ""}
function splitHostname() {
var result = {};
var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$');
var urlParts = regexParse.exec(window.location.hostname);
result.domain = urlParts[1];
result.type = urlParts[2];
result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);;
return result;
}
console.log(splitHostname());
This method only returns the subdomain as a string:
function getSubdomain(hostname) {
var regexParse = new RegExp('[a-z\-0-9]{2,63}\.[a-z\.]{2,5}$');
var urlParts = regexParse.exec(hostname);
return hostname.replace(urlParts[0],'').slice(0, -1);
}
console.log(getSubdomain(window.location.hostname));
// for use in node with express: getSubdomain(req.hostname)
These two methods will work for most common domains (including co.uk)
NOTE: the slice at the end of sub domains is to remove the extra dot.
I hope this solves your problem.
The solutions provided here work some of the time, or even most of the time, but not everywhere. To the best of my knowledge, the best way to find the full subdomain of any domain (and remember, sometimes subdomains have periods in them too! You can have sub-subdomains, etc) is to use the Public Suffix List, which is maintained by Mozilla.
The part of the URL that isn't in the Public Suffix List is the subdomain plus the domain itself, joined by a dot. Once you remove the public suffix, you can remove the domain and have just the subdomain left by removing the last segment between the dots.
Let's look at a complicated example. Say you're testing sub.sub.example.pvt.k12.ma.us. pvt.k12.ma.us is a public suffix, believe it or not! So if you used the Public Suffix List, you'd be able to quickly turn that into sub.sub.example by removing the known suffix. Then you could go from sub.sub.example to just sub.sub after stripping off the last portion of the remaining pieces, which was the domain. sub.sub is your subdomain.
This could work in most cases except for the one that #jlbang mention
const split=location.host.split(".");
let subdomain="";
let domain="";
if(split.length==1){//localHost
domain=split[0];
}else if(split.length==2){//sub.localHost or example.com
if(split[1].includes("localhost")){//sub.localHost
domain=split[1];
subdomain=split[0];
}else{//example.com
domain=split.join(".");
}
}else{//sub2.sub.localHost or sub2.sub.example.com or sub.example.com or example.com.ec sub.example.com.ec or ... etc
const last=split[split.length-1];
const lastLast=split[split.length-2];
if(last.includes("localhost")){//sub2.sub.localHost
domain=last;
subdomain=split.slice(0,split.length-1).join(".");
}else if(last.length==2 && lastLast.length<=3){//example.com.ec or sub.example.com.ec
domain=split.slice(split.length-3,split.length).join(".");
if(split.length>3){//sub.example.com.ec
subdomain=split.slice(0,split.length-3).join(".");
}
}else{//sub2.sub.example.com
domain=split.slice(split.length-2,split.length).join(".");
subdomain=split.slice(0,split.length-2).join(".");
}
}
const newUrl = 'http://example.com/some/path/here/' + subdomain
I adapted Vlad's solution in modern Typescript:
const splitHostname = (
hostname: string
): { domain: string; type: string; subdomain: string } | undefined => {
var urlParts = /([a-z-0-9]{2,63}).([a-z.]{2,5})$/.exec(hostname);
if (!urlParts) return;
const [, domain, type] = urlParts;
const subdomain = hostname.replace(`${domain}.${type}`, "").slice(0, -1);
return {
domain,
type,
subdomain,
};
};
get a subdomain from URL
function getSubdomain(url) {
url = url.replace( "https://www.","");
url = url.replace( "http://www.","");
url = url.replace( "https://","");
url = url.replace("http://", "");
var temp = url.split("/");
if (temp.length > 0) {
var temp2 = temp[0].split(".");
if (temp2.length > 2) {
return temp2[0];
}
else {
return "";
}
}
return "";
}