How would I go about trimming/stripping the URL down to get specific data...
So: https://www.example.com/items/423455344/size-39
Would become: 423455344
Any ideas?
If you know the URL is always going to match that format, you could do something like this.
function getData() {
let foo = window.location.href.split("/"); //this gives you an array with the data between the slashes
let searchController = "items"; //this is the key before the data you need
for (let i=0; i<foo.length; i++){
if (foo[i] === searchController){
searchController = "/true/";
} else if (searchController === "/true/") {
return foo[i];
}
}
}
Let me know if you have any questions
Related
I would like to achieve the following:
I have a URL: https://www.example.com/Place/Name.html?randomtext
I need to return "Name" only on outgoing links.
I thought it would work by doing the following:
function() {
if ({{outgoing link}})
var Name= {{Click URL}};
return Name.split("/")[2];
return Name.split("?")[0];
}
I already managed to get "place" by doing:
function() {
if ({{outgoing link}})
var Name= {{Click URL}};
return Name.split("/")[2];
One way to get the filename ("Name") would be to do:
var filename = url.substring(url.lastIndexOf('/')+1).split(".")[0]
https://codesandbox.io/s/magical-roman-uerpcp?file=/src/index.js
not sure if this is what u want:
const url = 'https://www.example.com/Place/Name.html?randomtext'
function extractSliceFromUrl() {
return url.split("/")[4].split(".")[0];
}
const url = 'https://www.example.com/Place/Name.html?randomtext'
function extractSliceFromUrl() {
return url.split("/")[4].split(".")[0];
}
console.log(extractSliceFromUrl(url))
console.log(extractSliceFromUrl(url))
So I'm using googlesheets. They have a scripteditor using google apps script https://developers.google.com/apps-script/guides/sheets.
Basically JavaScript.
I wanted to create a function that runs down a JSON file outputting what I specifically want. For example out of file:
{"meta":{"code":200,"disclaimer":"Usage subject to terms: https:\/\/fake-website.com\/terms"},"response":{"date":"2020-04-30T12:37:54Z","base":"X","rates":{"X":1,"F":0.9199812,"K":0.79896235,...}}}
I want to access the rates of F. So when I call my function it outputs 0.9199812.
The function I wrote looks like this:
function IMPORTJSON(url,xpath){
try{
// Funktion um in dem sheet das abzurufen /rates/F
let res = UrlFetchApp.fetch(url);
//get the url
let content = res.getContentText();
// get the content
let json = Json.parse(content);
//show content
let patharray = xpath.split(".")
//enables me to use dots to walk down the filepath
for( let i=0;i<patharray.lenght;i++){
//loop to only show what excactly I want out of the file
//json becomes what I want out of the file
json = json[patharray[i]];
}
//check whether json is an object
if(typeof(json) === "undefined"){
return "Node Not Available"; // In case I don't get an response
} else if(typeof(json) === "object"){
let tempArr = [];
//Creation of an array
for (let obj in json){
//filling the array with name and rate
tempArr.push([obj, json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting JSON data";
}
}
I tried to call it like this: IMPORTJSON(myurl, rates.F) but my sheet told me there's an error parsing the formula...
The link definitely works so there has to be an error with either my call (rates.F) or with my way of defining the call.
Please help.
Fetching is an async task and needs time to complete, so only after that time let res = UrlFetchApp.fetch(url); has value. But other codes will run immediately before res value resolved to something meaningful.
To make function an async function and for async task use await keyword, basically await means wait here and don't go forward until you got the result, so you can write your function like this:
async function IMPORTJSON(url,xpath){
try{
// Funktion um in dem sheet das abzurufen /rates/F
let res = await UrlFetchApp.fetch(url);
//get the url
let content = await res.getContentText();
// get the content
let json = JSON.parse(content);
//show content
let patharray = xpath.split(".")
//enables me to use dots to walk down the filepath
for( let i=0;i<patharray.lenght;i++){
//loop to only show what excactly I want out of the file
//json becomes what I want out of the file
json = json[patharray[i]];
}
//check whether json is an object
if(typeof(json) === "undefined"){
return "Node Not Available"; // In case I don't get an response
} else if(typeof(json) === "object"){
let tempArr = [];
//Creation of an array
for (let obj in json){
//filling the array with name and rate
tempArr.push([obj, json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting JSON data";
}
}
I have a list or URLs that I need to add a body class to. The list of URLs are found in the queryStrings variable. Here is my current code:
var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);
if (allPresent == false) {
} else {
document.body.classList.add("module-ads");
}
function CheckIfAllQueryStringsExist(url, qsCollection) {
for (var i = 0; i < qsCollection.length; i++) {
if (url.indexOf(qsCollection[i]) == -1) {
return false;
}
}
return true;
}
Right now, allPresent equals false even if I am on the page www.site.com/test.
Your CheckIfAllQueryStringsExist is wrong.
Change it to:
function CheckIfAllQueryStringsExist(url, qsCollection) {
for (var i = 0; i < qsCollection.length; i++) {
if (url.indexOf(qsCollection[i]) != -1) {
return true;
}
}
return false;
}
Your are checking the URL to see if it contains the array, which is backward.
Also, you don't need any loops here. Just check the array for the existence of the current URL and instead of an empty true branch to your first if statement, just reverse the test logic so that you can just have one branch.
var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);
if (allPresent) {
document.body.classList.add("module-ads");
}
function CheckIfAllQueryStringsExist(url, qsCollection) {
// Just return whether the array contains the url
return qsCollection.indexOf(url) > -1;
}
take a look at the window.location object, that will give you many other ways to match your url.
https://developer.mozilla.org/en-US/docs/Web/API/Location
href will return the protocol, so you could just tack on "https://" + to each href check, or you could use location.pathname or something.
You can use an array function .includes() to do your check. Otherwise, #gaetanoM answer is the answer you're looking for.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = queryStrings.includes(myUrl);
if (allPresent == false) {
// do something
} else {
document.body.classList.add("module-ads");
}
My project (with HTML and JavaScript) doesn't work in Internet Explorer and I think that is because I use a let statement in a JS method. Can I add some external libraries that makes it possible to read the let statements? Or can I rewrite the function? I don't really know how the let method works so can anyone tell me how to rewrite these lines:
initializeData = function()
{
//Check URL and QueryString
var url = window.location.href.toString();
var queryString = (url.split("?"))[1];
if (queryString == undefined || queryString=="" || queryString==null)
resetData();
else //filter data based on URL QueryString
{
const query = decodeURI(queryString);
const result = query.split('&');
result.forEach(function(item){
const [cat, values] = item.split('='); //ERROR
const isArray = cat.endsWith('[]');
let pair;
if (isArray)
{
const p = values;
pair = { cat, 'values': [values] };
}
else
{
pair = {cat, values };
}
currentFilters.push(pair);
});
RunFilter();
}
}
I need pair to be on the same structure since I am using it in the RunFilter() method.
My knowledge of front end it is not so good, and I don't know how to send array of ids to back end which will get all data and will be open it into new page. pls help
there my function:
#has_session_params('tin')
def print_documents(request):
doc_ids = request.POST.getlist('doc_ids[]')
tin = request.session['tin']
params = dict()
template = 'documents/documents_to_print.html'
params['Docs'] = docs
params['pb'] = pb
params['is_pdf'] = request.GET.get('is_pdf', 'false')
params['host'] = request.scheme + "://" + request.META["HTTP_HOST"]
params['url'] = settings.SITE_URL + request.get_full_path()
params['doc_type'] = INVOICE_TYPE
invoice_list = list()
for doc_id in doc_ids:
response = proxy.get_invoice_by_id(invoice_id=doc_id, tin=tin)
if response.status.code != pb.ResponseStatus.OK:
response = proxy.get_invoice_draft_by_id(
invoice_draft_id=doc_id, tin=tin)
invoice_list.append(response.invoice)
params['invoices'] = invoice_list
return render(request, template, params)
I know how to get one object by id, it will be like:
def print_document(request, doc_id):
and something like that, and where url for function will be look like that:
url(r'^print_documents/(?P<doc_id>[a-z\d]{24})/$', invoices.print_documents, name='print_documents')
and new page link will be like that localhost:8000/documents/print_documents/{doc_id}
and this method I can just call like :
print
but now I want to select several documents and send doc_ids, and I know that I can to like method above but I don't want big link. And how I can send array of ids to back end correctly?
now I have something like that:
printAll.on("click", function(){
var invoicesID = [];
$('input.select-inv-check:checked').each(function() {
invoicesID.push($(this).data('docid'));
});
var url = Globals.printAll;
$.post( url, { doc_ids: invoicesID } ).done(function(result) {
console.log("result", result[0].Docs);
if(result.code == 0){
}else{
alert(result.message);
}
});
});
And I know that it doesn't correct! pls help