Grab YouTube ID and additional variables for embedding purposes with JavaScript - javascript

So I've seen lots of scripts to grab the YouTube ID from a URL with JavaScript, but I can't find or figure out how to grab the ID along with any additional variables. I have a PHP script which can do it, but I'd like to do this with JavaScript. Does anyone know how this can be accomplished?
I doubt it's necessary but here are the two scripts I'm using
JavaScript for video ID...
url = $(this).text();
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[2].length==11){
alert(match[2]);
}else{
alert("not youtube");
}
And PHP...
if (preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
$youtubeid = $match[1];
$getyt = (parse_url($url));
}
if(strlen($getyt['fragment']) > 0) {
$addhash = '#' . $getyt['fragment'];
}
$embed = "http://www.youtube.com/embed/$youtubeid?wmode=opaque&autoplay=1$addhash";
The PHP one is pretty good, except that it only works for hash tags. My primary reason for wanting the additional variables is for when someone wants to specify a start time. So if anyone can tell me how I can grab the URL and additional paramaters (or just the specified starting time of the video) then I'd really appreciate it, because I'm absolutely lost.

This creates an associative array named video_parameters:
function extractParameters(url)
{
var query = url.match(/.*\?(.*)/)[1];
var assignments = query.split("&")
var pair, parameters = {};
for (var ii = 0; ii < assignments.length; ii++)
{
pair = assignments[ii].split("=");
parameters[pair[0]] = pair[1];
}
return parameters;
}
url = "http://www.youtube.com/watch?v=gkU&list=UUa3Q&feature=plcp";
video_parameters = extractParameters(url);
// video_parameters["v"]
// > "gkU"
// video_parameters["list"]
// > "UUa3Q"
See How can I get query string values in JavaScript? for methods that handle special chars.

Related

Read variables from a file in Javascript

I have a variable called words in Javascript like this:
var words = [{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"},
{"text":"Minutify", "url":"http://minutify.com/"}]
and I use the variable elements as for example words[0].url which points to the first url, i.e http://google.com/, etc.
If I store the data in a file like this (I call it file.csv):
This, http://google.com/
is, http://bing.com/
some, http://somewhere.com/
random, http://random.org/
text, http://text.com/
InCoMobi, http://incomobi.com/
Yahoo, http://yahoo.com/
Minutify, http://minutify.com/
How can I read the file in Javascrip and re-create variable words, with the exact same format as I mentioned earlier, i.e re-create:
var words = [{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"},
{"text":"Minutify", "url":"http://minutify.com/"}]
It looks like there are two steps. First is to get the external file, and the next step is to get it into a format you want it.
If you're not using jquery, first step is:
var file = new XMLHttpRequest();
file.onload = function() {
alert(file.responseText);
}
file.open('GET', 'file.csv');
file.send();
Next step is to take that file.responseText and format it. I might do:
var file = new XMLHttpRequest();
var words = [];
file.onload = function() {
var lines = file.responseText.split("\n");
for (var i = 0; i < lines.length; i++) {
var word = {};
var attributes = lines[i].split(",");
word.text = attributes[0];
word.url = attributes[1];
words.push(word);
}
}
file.open('GET', 'file.csv');
file.send();
If you're using a JSON file, just change the function above to be:
file.onload = function() {
words = JSON.parse(file.responseText);
}
Keep in mind that the words variable will not be available until the onload function runs, so you should probably send it to another function that uses it.
You could use the fetch API, it has many advantages and one of them is very short syntax, unlike the XMLHttpRequest constructor.
fetch("object.json").then(function(data){window.data=data.json()});
//then access the data via [window.data]

Google Script to see if text contains a value

I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automatically send an email but I need it formatted in a way that my user can edit it later.
There are some check boxes on the form -- but the getResponse() is only populated with the items checked and I need it to show all possible choices. Then I will indicate somehow what was checked.
I can't find a way to see if a text contains a value.
Like in Java with a String, I could do either .contains("9th") or .indexOf("9th") >=0 and then I would know that the String contains 9th. How can I do this with google scripts? Looked all through documentation and I feel like it must be the easiest thing ever.
var grade = itemResponse.getResponse();
Need to see if grade contains 9th.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Update 2020:
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');

passing alphanumeric value in querystring in url does not work in flash

I am having a flash application where I want to send paramters to it via the javascript from a defaul.aspx page.
I have a paramter called Id where it can accept alphanumerica values.
the query string in the url works fine if I enter just numbers for the Id, and takes me to the specific page relted to that id , but if I enter a combination of numbers and characters like 001A , it does not work.
this is the code I used
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i<vars.length; i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
return (pair[1]);
}
}
</script>
and then later I assigned the first page of flash application to it.
flashvars.StartPage = getQueryVariable("Id");
and then passed the flashvars into swfobject.embedSWF
I also don't want to change anything in my mxml files in flash side
I appreciate if anyone could help me what the problem is
thanks
No you don't need to use JavaScript to process the value from querystring and then to send to flash.
Just make use of ExternalInterface.call function to grab variables (In this case : GET ) from URL.
Here's the code how it works. Add this code inside your MXML.
var pageURL : String = ExternalInterface.call("window.location.href.toString");
var paramPairs : Array = pageURL.split("?")[1].split("&");
for each (var pair : String in paramPairs)
{
var pairHolderx:Array = pair.split("=");
arrVals[counter]=pairHolderx[1];
counter++;
}
So if your URL is like http://www.stackoverflow.com/page.aspx?id=230A78&id2=8934
The arrVals[0] contains 230A78 and arrVals[1] contains 8934

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Accessing CGI values with Prototype

Anyone know the quickest way to grab the value of a CGI variable in the current URL using Prototype? So if I get redirected to a page with the following URL:
http://mysite.com/content?x=foobar
I am interested in retrieving the value of "x" (should be "foobar") in a function called on page load like this:
Event.observe(window, "load", my_fxn ());
Thanks
You may want to look at the parseQuery method. This should do all the splitting you'd expect on a standard querystring such as document.location.search
http://api.prototypejs.org/language/string.html#parsequery-instance_method
For example:
document.location.search.parseQuery()["x"];
Will be undefined if it's not present, and should be the value otherwise.
I couldn't find any shortcuts here, so in the end I just parsed the URL with js like so:
function my_fxn () {
var varsFromUrl = document.location.search;
// get rid of first char '?'
varsFromUrl = varsFromUrl.substring(1);
var pairsArray = varsFromUrl.split("&");
for (i = 0; i < pairsArray.length; i++) {
var pair = pairsArray[i].split("=");
if (pair[0] == "x")
alert(pair[1] + ' is what I want.');
}
}

Categories