I want to extract a part of a website address and append it to an other link.
Example: website.com/abc123 --> otherwebsite.com/abc123
Is there an easy way to do this?
I'm new to JavaScript
function returnNewAdress(adr, ows) {
return ows + adr.substring(adr.indexOf("/"), adr.length);
}
returnNewAdress("website.com/abc123", "otherwebsite.com");
function OtherURL(What) {
NewURL='otherwebsite.com';
return NewURL+'\/'+What.substring(What.lastIndexOf('\/'));
}
It's unclear in what environment the function should run.
In node.js you could do this:
var transformUrl = function (url, newDomain) {
if (! url.match(/https?:\/\//i)) {
// prepend URL with protocol if missing
url = "http://" + url;
}
return newDomain + require("url").parse(url).path;
};
// can be called like this:
// this will return 'otherwebsite.com/abc123'
transformUrl("website.com/abc123", "otherwebsite.com");
transformUrl("http://website.com/abc123", "otherwebsite.com");
Related
This question already has an answer here:
using variable results (contents) to create new variables
(1 answer)
Closed 10 months ago.
I have a list
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
how can I use these peoples numbers if their names matches another variable result?
We have
var name = *selected server-side student names*
and by these * signs I mean it's a great list that name gives up but it only gives up one name out of that list at the time we call it.
If one of these students is selected by name variable, how can I use the number defined in front of that name in const StudentCode to generate a url?
Suppose you get Rose! Then the number for Rose is: 35621548 and the url for example will be https://www.35621548.com. What code can we use to generate this url for example in console?
console.log(url)
Use this:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}
This function will return you the url on the basis of the student name that is passed in this function.
function returnURL(studentName){
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
if (!!!StudentCode[studentName]) return "";
return "https://" + StudentCode[studentName] + ".com";
}
console.log(returnURL("Rose"));
Hope, this helps!!
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
let studentName = "Jack"
const url = `https://${StudentCode[studentName]}.com`
console.log(url)
export const studentUrlModule = (function() {
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrl = function(code = '') {
if (!url) {
throw new Error('Url is not defined')
} else if (!code) {
throw new Error('Code is not defined')
};
return url.replace('$code', `${code}`);
}
function getCode(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
function getUrl(name = '') {
if (!name) {
throw new Error('StudentName is undefined')
};
const code = getCode(name);
const studentUrl = generateUrl(code);
return studentUrl;
}
return {
generateUrl,
getCode,
getUrl,
};
}());
Maybe it helps. If the code was not founded then it throws an error. Please use try, catch error handlers to handle errors.
-- Update
I updated the code and as you can see it's a module and you need to import it everywhere you like to use this.
if you are not familiar with modules and how to use them inside the browser check documents.
Mozila documents
Super Simple Start to ESModules in the Browser
So I'm needing to get the list of file names from a range of Google Drive URLs in a spreadsheet. Browsing around the net, I came across the code below. It works but only for the old style urls, which I heard Google changed in September 2021.
Note that links are not fully functional, please replace with real links to check!
The old style is:
https://drive.google.com/file/d/1GMUwYxZxsNpLiaYOiVMBwl41LpreQ-fc/view?usp=sharing
This works correctly from the code below.
What I'd like though is two things.
It should handle a range of a couple of columns, currently reading AE2:AE, and printing out on AM2:AM. What I'd like is to go through the range: AE2:AL and print out: AM2:AT
Secondly it should also handle the newer form urls:
https://drive.google.com/file/d/0B9EZQqsLDEqDUGlsdy1oVEtETGs/view?usp=sharing&resourcekey=0-h7HOcxayPaHJ5r6dAAslVQ
Current Code:
function getNames() {
var activeRange = SpreadsheetApp.getActiveSheet().getDataRange();
var height = activeRange.getHeight();
var links = SpreadsheetApp.getActiveSheet()
.getRange("AE2:AE" + height)
.getValues();
var nameValues = [];
links.forEach((row) => {
try {
var link = row[0];
var fileID = getIdFromLink(link);
var name = DriveApp.getFileById(fileID).getName();
nameValues.push([name]);
} catch (e) {
nameValues.push(["NO NAME FOUND"]);
}
});
var nameRange = SpreadsheetApp.getActiveSheet().getRange("AM2:AM" + height);
nameRange.setValues(nameValues);
}
function getIdFromLink(link) {
var regex = new RegExp(
/(?<=https:\/\/drive\.google\.com\/file\/d\/)(.+)(?=\/)/
);
return regex.exec(link)[0];
}
How should the code above be modified to enable what I'm wanting. Sorry, I tried a couple of if/else statements, but my Javascript knowledge is severely limited.
Any help would be greatly appreciated.
Current "screenshot" showing:
(1) - Old style url - correctly picking up file name (2)
(3) - New style url - not picking up file name (4)
Your getIdFromLink() function should work just fine as long as the files have not been shared in such a way that they require a resource key as well.
To work with resource keys, use DriveApp.getFileByIdAndResourceKey(), like this:
function getFileNamesByLink() {
const sheet = SpreadsheetApp.getActiveSheet();
const sourceRange = sheet.getRange('AE2:AL');
const targetRange = sheet.getRange('AM2');
const fileNames = sourceRange.getValues()
.map(row => row.map(link => getFileNameFromLink_(link)));
targetRange
.offset(0, 0, fileNames.length, fileNames[0].length)
.setValues(fileNames);
}
function getFileNameFromLink_(link) {
if (!link) {
return null;
}
const fileId = getIdFromLink_(link);
if (!fileId) {
return NaN;
}
let file;
try {
file = DriveApp.getFileById(fileId);
} catch (error) {
try {
file = DriveApp.getFileByIdAndResourceKey(fileId, getResourceKeyFromLink_(link));
} catch (error) {
return NaN;
}
}
return file.getName();
}
function getIdFromLink_(link) {
const match = String(link).match(/file\/d\/([-\w]+)/i);
return match ? match[1] : null;
}
function getResourceKeyFromLink_(link) {
const match = String(link).match(/resourcekey=([-\w]+)/i);
return match ? match[1] : null;
}
Note that the script may time out if you have thousands of links. If that happens, process the links in a piecemeal fashion, or see if the Advanced Drive Service works for you.
I'd appreciate any help.
I'm trying to change the link href each time with Kendo Grid change() event:
function ContractsGrid_onChange(e) {
var selected = this.select()[0],
item = this.dataItem(selected);
$('#createOnBase').attr('href', function () {
var createLink = document.getElementById("createOnBase");
var route = 'http://' + createLink.hostname + createLink.pathname + "?contractID =" + item.ID;
return route;
});
}
#Ajax.ActionLink("Create", "CreateOnBase",
new { contractID = "_contractID_" },
new AjaxOptions() {... },
new { id="createOnBase" })
I'm not sure with current approach, because i have different hostnames (localhost with port or server domain)
The best way would be:
var route = "#Url.Action('CreateOnBase', new { contractID = ??})";
But I cannot use JS variable (item.ID) in razor.
Also, this.href.replace("_contractID_", item.ID) won't work for several changes.
Can you help me with another solution?
Thanks a lot!
Yeh, that was easy, I found a way:
$('#createOnBase').attr('href', function () {
return "#Url.Action("CreateOnBase")"+ "/?contractID=" +item.ID;
});
maybe it will be helpful for someone.
The first thought that come up to my mind is to store root url in separate variable.Something like this:
function ContractsGrid_onChange(e) {
var selected = this.select()[0],
item = this.dataItem(selected);
var rootUrl = #Url.Action("Create", "CreateOnBase");
$('#createOnBase').attr('href', function () {
var createLink = document.getElementById("createOnBase");
var route = rootUrl + "?contractID =" + item.ID;
return route;
});
}
This is just a workaround, not sure about some advanced way...
Newbie question. Why is this JavaScript function returning undefined?
var redis = require("redis"), client = redis.createClient();
function generatePageUrl() {
var randomStr = randomInt.toString(32);
// Check whether this URL is already in our database;
client.smembers("url:" + randomStr, function (err, data ) {
if (data.length != 0) {
// URL already in use, try again
return getPageUrl();
}
return randomStr;
});
}
var page_url = generatePageUrl();
// add it to the database, etc
I guess it must be getting to the end and returning before it reaches the inside of client.smembers.
But I really need to check the contents of the Redis set before it returns: can I get it to return from inside the callback? If not, what can I do?
Also, advice on the way I've used this function recursively would be welcome - I'm not sure it's completely sensible :)
Thanks for helping out a newcomer.
You can't return from inside a callback. Do it like this:
var redis = require("redis"), client = redis.createClient();
function generatePageUrl(cb) {
var randomStr = randomInt.toString(32);
// Check whether this URL is already in our database;
client.smembers("url:" + randomStr, function (err, data ) {
if (data.length != 0) {
// URL already in use, try again
getPageUrl(cb);
}
cb(randomStr);
});
}
generatePageUrl(function(page_url){
// add it to the database, etc
});
If you don't like this style, you might want to consider streamlinejs - it makes you able to write your code like this:
var redis = require("redis"), client = redis.createClient();
function generatePageUrl(_) {
var randomStr = randomInt.toString(32);
// Check whether this URL is already in our database;
var data = client.smembers("url:" + randomStr, _);
if (data.length != 0) {
// URL already in use, try again
return getPageUrl(_);
}
return randomStr;
}
var page_url = generatePageUrl(_);
// add it to the database, etc
I am looking to write a piece of javascript that will do the following:
Look at current url and return any folders in the url ie:
http://localhost/folder1/page.aspx returns -> /folder1/
http://localhost/page.aspx returns -> /
Any help?
You can try window.location.pathname to get its path. for ref
window.location.pathname.substr(0, window.location.pathname.lastIndexOf("/") + 1);
Via window.location you can access the full URL of your running script. Then you can use a REGEX to extract the part you want, in this case the path.
The location property (on window) (link) has a variety of properties that you can use to get that information.
Here's an example of what's available:
var loc, name, value;
loc = window.location;
for (name in window.location) {
value = loc[name];
if (typeof value != 'function') {
display(name + ": " + value);
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}