R string replacing part of javascript - javascript

I'm sure this is a noob question but I couldn't figure out how you would insert a R string object inside a javascript. For example,
trackname <- "audiotrack1"
into
tag$script(var url = 'audioResources/' + trackname + '.wav')
Where I would want to replace the "trackname" with "audiotrack1". I'm sure paste0 isn't the best way to do this. What is the standard way to go about doing this?
Many thanks.

This is not correct. You can do:
tags$script(HTML(sprintf("var url = 'audioResources/%s.wav'", trackname)))

An option with glue
library(glue)
tags$script(HTML(glue::glue("var url = 'audioResources/{trackname}.wav'")))

Related

How to get last two URL segments?

What is the best way to get the last two URL segments?
To get the last segment is pretty easy url.substr(url.lastIndexOf('/') + 1)
Here is an example, say I have this url http://mywebsite/segment1/segment2
So I want to get segment1/segment2
Is there a better way than just using url.split("/");?
Splitting, slicing and joining is probably the easiest:
const url = 'http://mywebsite/segment1/segment2';
const lastTwo = url.split('/').slice(-2).join('/');
console.log(lastTwo);
You can use this as a reference :
Take out the pathname, and then do the string.split, it would also protect you from the content after the ? sign (url parameters).

How to extract specific parameter from different URLs

I've looked on similiar topics but no one seems to answer my question.
I've URL that looks like this:
https://dummy.com/job/test
I need to extract test so I am using:
function getIdentificator(){
let URL = window.location.pathname;
let Id = URL.slice(URL.lastIndexOf('/') + 1);
return Id;
}
It gives me what I want but sometimes the URL is different. For example:
https://dummy.com/job/testwz/something
I only need testwz.
Or:
https://dummy.com/job/test-ab?somethingmore2132
I only need test-ab.
Or:
https://dummy.com/job/test
I only need test.
Or:
https://dummy.com/job/5423
I need 5423 from this.
Value I'm interested in always appear after job/ but in different variations as said before. Key value may be followed by: nothing, / or ?.
Is there any way to extract this value in all examples with JavaScript? If not I can use jQuery as well.
Assuming your path will always begin with /job no matter the domain:
return window.location.pathname.split('/')[2]
I'm going to give you this example:
this is the question's url:
https://stackoverflow.com/questions/54556911/how-to-extract-specific-parameter-from-different-urls
if you do window.location.pathname you will get :
"/questions/54556911/how-to-extract-specific-parameter-from-different-urls"
now, if you do...
window.location.pathname.split('/').pop()
you will get:
how-to-extract-specific-parameter-from-different-urls
And I think this is the answer you are looking for.

applescript with javascript -> get string from href

I try to read out the string inside of an unordered list .
The string of interest is the following number: href="?notation=1549220"
image
I am very new to HTML/CSS/JavaScript so please excuse this simple question.
I tried something like this, but it's getting nowhere:
document.getElementById('exchangesLayerHs')
.getElementsByTagName('ul')
.getElementsByTagName('li')
.getElementsByTagName('a');
Has anyone a tipp for me?
Thanks a lot!
Carlo
You could get the link with the title handelsplatz geschlossen :
var link = document.querySelector("a [title='Handelsplatz geschlossen']");
Now simply get the thing behind = in the href and convert it to a number (+) :
var result = + link.href.split("=")[1];

How to get base url from FTP address?

For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.

Break a URL into its components

I'm using javascript and would like to take a URL string that I have and break it down into its components such as the host, path, and query arguments.
I need to do this in order to get to one of the query arguments, which is itself a URL and is thus encoded in the original URL string.
I feel like there should be an easy way to do this in Javascript. Perhaps something that looks like this:
var what_I_Want = url("http://www.domain.com?queryArg1=somequeryargument").getQueryArgumentValue("queryArg1");
The parseUri function will do everything you need
Edit
Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.
<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>
Hope this will help..
In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested
Also you can use parseUri as Tak suggested
There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme
Example:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'
Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:
a = "http://www.domain.com?queryArg1=somequeryargument";
query = a.substring(a.indexOf('?')+1);
You could then split the query up based on the &'s and again on the = to get at whatever param you need.
Sorry if this ain't very helpful as its a bit of a low tech method :P
EDIT:
Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)
//Quick and dirty query Getter object.
function urlQueryGetter(url){
//array to store params
var qParam = new Array();
//function to get param
this.getParam = function(x){
return qParam[x];
}
//parse url
query = url.substring(url.indexOf('?')+1);
query_items = query.split('&');
for(i=0; i<query_items.length;i++){
s = query_items[i].split('=');
qParam[s[0]] = s[1];
}
}
//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));

Categories

Resources