I'd like to loop through list items onload and detect whether or not they have a YouTube URL and use the video id from the URL in an iframe. This is what I've done so far but it's not working:
$('li').each(function() {
var url = $(this).text();
if (url != undefined || url != '') {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
// Do anything for being valid
// if need to change the url to embed url then use below line
$(this).find('.videoObject').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=0&enablejsapi=1').show();
} else {
// Do anything for not being valid
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
foo
<iframe class="videoObject" src=""></iframe>
</li>
<li>
bar
<iframe class="videoObject" src=""></iframe>
</li>
<li>
foo https://www.youtube.com/watch?v=Vr3ya_uPmxg
<iframe class="videoObject" src=""></iframe>
</li>
</ul>
jsFiddle
I prefer you to create virtual A element, then you get access to some helpful DOM methods to parse it's href value like hostname, protocol, pathname, search, hash, etc. Then it's easier to validate the url parts. I wrote a small function, it returns:
false if the URL is not youtube url,
empty string if it is youtube url but without video ID
string id.
var links =
['https://youtube.com/watch?v=01jcwGApTWA',
'https://youtube.com/watch?v=01jcwGApTWA&t',
'https://youtu.be/01jcwGApTWA?t=31',
'https://www.youtube.com/watch?v=Ujqdle7CvIU&spfreload=10',
'https://www.youtube.com/watch?v=nQ9ww9E_1C4',
'https://www.youtube.com/embed/nQ9ww9E_1C4',
'https://www.youtube.com/embed/nQ9ww9E_1C4?autoplay=1',
'https://www.youtube.com/embed/nQ9ww9E_1C4?playlist=XGSy3_Czz8k&loop=1',
'https://www.youtube.com',
'http://anothersite.com'];
function isYoutube(getURL){
if(typeof getURL!=='string') return false;
var newA = document.createElement('A');
newA.href = getURL;
var host = newA.hostname;
var srch = newA.search;
var path = newA.pathname;
if(host.search(/youtube\.com|youtu\.be/)===-1) return false;
if(host.search(/youtu\.be/)!==-1) return path.slice(1);
if(path.search(/embed/)!==-1) return /embed\/([A-z0-9]+)(\&|$)/.exec(path)[1];
var getId = /v=([A-z0-9]+)(\&|$)/.exec(srch);
if(host.search(/youtube\.com/)!==-1) return !getId ? '':getId[1];
}
console.log(isYoutube(links[0]));
console.log(isYoutube(links[1]));
console.log(isYoutube(links[2]));
console.log(isYoutube(links[3]));
console.log(isYoutube(links[4]));
console.log(isYoutube(links[5]));
console.log(isYoutube(links[6]));
console.log(isYoutube(links[7]));
console.log(isYoutube(links[8]));
console.log(isYoutube(links[9]));
Related
i am using javascript code to get html content from one the pages, while at the same time i also want to change the content i get from html (inside the carttitle id). how can i change the value of id=carttitle on the cartbox.html below dynamically?
this is the code (div where the html will be located)
<!-- index.html -->
<!-- button to trigger the function -->
<button onclick="getcontent('cartbox.html','#cartboxes','#cartbox');">getcontent</button> <!-- the cartbox.html will fill the content below -->
<ul class="cartboxes" id="cartboxes">
</ul>
this is the javascript code function to get the html
// select.js
function getcontent(url, from, to) {
var cached = sessionStorage[url];
if (!from) {
from = "body";
} // default to grabbing body tag
if (to && to.split) {
to = document.querySelector(to);
} // a string TO turns into an element
if (!to) {
to = document.querySelector(from);
} // default re-using the source elm as the target elm
if (cached) {
return to.innerHTML = cached;
} // cache responses for instant re-use re-use
var XHRt = new XMLHttpRequest; // new ajax
XHRt.responseType = 'document'; // ajax2 context and onload() event
XHRt.onload = function() {
sessionStorage[url] = to.innerHTML = XHRt.response.querySelector(from).innerHTML;
};
XHRt.open("GET", url, true);
XHRt.send();
return XHRt;
}
this is the html code that i will get the content from
<!-- cartbox.html -->
<div id="cartbox">
<li>
<div class="cartbox">
<div class="cartboxleft">
<img src="img/search.png" width="60px" height="60px">
</div>
<div class="cartboxright">
<!-- i want to change the value of the carttitle below dynamically -->
<b class="carttitle" id="carttitle">nice Pizza</b>
<p class="cartdescription">Number: <b>1</b></p>
<p class="cartdescription">Price: <b>$ 11.22</b></p>
</div>
<div class="cartboxdelete">
<button class="deletebutton" onclick="deleteitem(this);">X</button>
</div>
</div>
</li>
</div>
You should use responseType = 'text' as document responseType is not recommended to avoids wasting time parsing HTML uselessly. Now regarding your issue, you can do like this:
function getcontent(url, fromSelector, toSelector) {
var cached = sessionStorage[url];
if (cached) {
return toSelector.innerHTML = cached;
}
fromSelector = fromSelector || 'body';
toSelector = toSelector && document.querySelector(toSelector) || document.querySelector(fromSelector);
var XHRt = new XMLHttpRequest();
XHRt.open("GET", url, true);
XHRt.responseType = 'text';
XHRt.onload = function() {
if (XHRt.readyState === XHRt.DONE && XHRt.status === 200) {
toSelector.innerHTML = XHRt.responseText;
document.getElementById('carttitle').innerHTML = 'your new value';
sessionStorage[url] = toSelector.innerHTML; // Now it will work after loading from session storage.
}
};
XHRt.send();
}
Your cache process will not work because you are selecting a property with the brackets operator [] on the session storage object.
Instead use the getItem() method to get the key that you are looking for.
var cached = sessionStorage.getItem(url);
In your second if statement you check to and to.split. Unless the to string has a split property, this will fail. Your intentions here seem unknown. Instead just check for the string to be a valid string instead.
if (to && 'string' === typeof to) {
The part where you create a new instance of XMLHttpRequest will fail because you are missing the parenthesis to call the constructor.
var XHRt = new XMLHttpRequest();
Then in your onload callback you have to save the innerHTML of your result in the session storage using the setItem() method.
But before doing that, select the cart title element with querySelector and change the content of the element if you need it to.
XHRt.onload = function() {
let element = this.response.querySelector(from);
if (element !== null) {
let cartTitle = element.querySelector('#carttitle');
cartTitle.textContent = 'An even better pizza';
let html = element.innerHTML;
to.innerHTML = html;
sessionStorage.setItem(url, html);
}
};
I have function, which shows / outputs the urls from the textarea. At the moment however it won't merge duplicates into 1 URL. How can I output same urls as one (Merge http://google.com, www.google.com, http://www.google.com, or just google.com)?
At the moment:
Should be:
My Code:
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/[^\s]+)/g;
$("#textarea").val().replace(urlRegex, function(url) {
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<div id="converted_url"></div>
JS FIDDLE
Credits
Scott Marcus, Stackoverflow
Simple fix: store matched urls in array and append link only if url is not present in that array.
UPDATE: changed regex to /((https?:\/\/|www\.|\/\/)[^\s]+)/g so it matches links starting with http://, https://, www., //. You may use any other regex covering other cases (like http://www.) just modify stored url so that you'll be able to compare it (you may want to treat http and https link as unique).
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /((https?:\/\/|www\.|\/\/)[^\s]+)/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
let trimmedUrl = url.replace(/^(https?:\/\/|www\.|\/\/)/, "");
if (found.includes(trimmedUrl)) {
return;
}
found.push(trimmedUrl);
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
var link = "";
var protOmmitedURL = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
if (found.includes(protOmmitedURL)) {
return;
}else
{
link = '<div>' + url + '</div>';
found.push(protOmmitedURL);
}
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
I am using Autolinker.js to linkify text inputted from a form, but I would like to exclude example.com from being linked.
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = Autolinker.link(formInput);
naturally yields linkedText having both urls linkified. I tried changing the url options using
var options = {urls: { schemeMatches: true, wwwMatches: true, tldMatches: false }};
var linkedText = Autolinker.link(formInput, options);
but this eliminates the link on google.com as well as the example.com while leaving www.kbb.com linked.
Basically I just want to exclude a single specific url, namely example.com, from being linked.
Sorry that I just noticed this thread. I'm the library author. I know it's pretty late but leaving this reply for anyone else who comes across it.
The easiest way to exclude a particular url from being autolinked is to leverage the replaceFn option. For example:
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = Autolinker.link( formInput, {
replaceFn: function( match ) {
if( match.getType() === 'url' ) {
var url = match.getUrl();
if( url.indexOf( 'example.com' ) !== -1 ) {
return false; // don't autolink matches for example.com
}
}
return true; // autolink everything else as usual
}
} );
This produces the result of:
Don't link example.com but link google.com and kbb.com please
Here is some documentation on the methods that can be called on UrlMatch objects: http://greg-jacobs.com/Autolinker.js/api/#!/api/Autolinker.match.Url
And a more in-depth example of using replaceFn: https://github.com/gregjacobs/Autolinker.js#custom-replacement-function
Replace text with a token, run autolink, replace token with original text. The obvious weakness here is that if formInput contained ||anything|| it would break.
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var stuffIdontwanttolink = ['example.com', 'google.com'];
stuffIdontwanttolink.forEach(function(entry, index) {
formInput = formInput.replace(entry, '||' + index + '||');
});
console.log(formInput);
//var linkedText = Autolinker.link(formInput);
var linkedText = "Don't link ||0|| but link ||1|| and <a href='//www.kbb.com'>www.kbb.com</a> please"; // Simulated
stuffIdontwanttolink.forEach(function(entry, index) {
linkedText = linkedText.replace('||' + index + '||', entry);
});
console.log(linkedText);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
So I wrote a function to wrap the Autolinker in:
function excludedLinkify (inputText) {
var exclusions = [
{url:'example.com', temp:'7g578v43gc7n3744c'}
];
$.each(exclusions, function (i, e) {
inputText = inputText.replace(e.url, e.temp);
});
inputText = Autolinker.link(inputText);
$.each(exclusions, function (i, e) {
inputText = inputText.replace(e.temp, e.url);
});
return inputText;
}
So that to achieve the desired result I can now
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = excludedLinkify(formInput);
Previous stackoverflow
This jquery statement will look for domain.com and append ?parameter to the end of the URL. It will NOT append if ?parameter has already been added.
The problem: My current jquery modifies all URLs and not domain.com. Here is the regex statement that i would like to use and is tested to work. However, when implemented, nothing is appended. Any help is greatly appreciated!
Regex i would like to use:
\b(https?://)?([a-z0-9-]+\.)*domain\.com(/[^\s]*)?
RegexFiddle
JSFiddle for convience
Code to be modified
<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content"><a title="Link to test domain" href="http://www.domain.com">Link to google</a>
<a href="http://www.google.com/directory/subdirectory/index.html">This is another link</a>
<a href="http://domain.com/directory/index.html">This is a 3rd link</a>
<a href="http://www.domain.com/subdir?parameter">this url already has parameters</a></textarea></div>
current jquery statement
var url = 'www.domain.com';
var append = '?parameter';
$(".wp-editor-area").each(function() {
$(this).text(urlify($(this).text()));
});
function urlify(text) {
var urlRegex = /(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
// if the url does not contain append, concat append to the URL
if (url.indexOf(append) == -1) {
return url + append;
}
return url;
});
}
Current output
<a title="Link to test domain" href="http://www.domain.com?parameter">Link to google</a>
This is another link
This is a 3rd link
Test this code - it should be what you need (or at least starting point) >>
function urlify(text) {
var append = '?parameter';
text = text.replace(/("(?:(?:https?|ftp|file):\/\/)?(?:www.|)domain.com(?:\/[-a-z\d_.]+)*)(\?[^"]*|)(")/ig,
function(m, m1, m2, m3) {
return ((m1.length != 0) && (m2.length == 0)) ? m1 + append + m3 : m;
});
return text;
}
$(".wp-editor-area").each(function() {
this.innerHTML = urlify(this.innerHTML);
});
I have a url variable http://blah.com/blah/blah/blah and I have another url http://shop.blah.com/ I want to take the first url (blah.com) and add the ending blah/blah/blah to the second url http://shop.blah.com
So I end up with http://shop.blah.com/blah/blah/blah
Any idea of how I could do this?
var url1 = 'http://blah.com/blah/blah/blah';
var url2 = 'http://shop.blah.com/';
var newUrl = url2 + url1.replace(/^.+?\..+?\//, '');
It sounds like the jQuery-URL-Parser plugin might come in handy here:
var url = $.url(); //retrieves current url
You can also get specific parts of the URL like this:
var file = $.url.attr("file");
var path = $.url.attr("path");
var host = $.url.attr("host");
...
If you need to get Querystring parameters:
var parm = $.url.param("id");
If the intent is just to add shop to the front of the domain name:
var url2 = url1.replace('://', '://shop.');
<script>
$(document).ready(function(){
//this uses the browser to create an anchor
var blah = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
blah.href = "http://blah.com/blah/blah/blah?moreBlah=helloWorld#hashMark";
var shop = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
shop.href = "http://shop.blah.com/";
shop.pathname = blah.pathname; //the blahs
shop.search = blah.search; //the blah query
shop.hash = blah.hash; // the blah hashMark
alert("These are the droids you're looking for: "+shop.href);
});
</script>