YouTube replace url with video ID using JavaScript and jQuery - javascript

i have taken the regex from this http://jsfiddle.net/HfqmE/1/
I have the HTML
<span class="yturl">http://www.youtube.com/watch?feature=endscreen&NR=1&v=jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/watch?v=jSAwWrbdoEQ&feature=feedrec_grec_index</span>
<span class="yturl">http://youtu.be/jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/embed/jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/v/jSAwWrbdoEQ?version=3&hl=en_US</span>
<span class="yturl">http://www.youtube.com/watch?NR=1&feature=endscreen&v=jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/user/TheGameVEVO#p/a/u/1/jSAwWrbdoEQ</span>
for each span.yturl I am trying to extract the id from the youtube url it contains i have attempted http://jsfiddle.net/HfqmE/40/
$("span.yturl").each(function(){
var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var youtubeurl = $("span.yturl").html();
var regexyoutubeurl = youtubeurl.match(regex);
$("span.yturl").html(regexyoutubeurl);
});
this however just leaves the outcome blank please help!!

Match returns an Array. It looks like you want regexyoutubeurl[2].
You are re-querying $("span.yturl") inside your iterator function. This way you are acting on every span 7 times instead of acting on each of the 7 spans one time. Use $(this) instead.
Also, use .text() instead of .html(), lest your & becomes &.
$("span.yturl").each(function(){
var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var youtubeurl = $(this).text();
var regexyoutubeurl = youtubeurl.match(regex);
if (regexyoutubeurl) {
$(this).text(regexyoutubeurl[2]);
}
});
http://jsfiddle.net/gilly3/HfqmE/53/

<script>
var LockedTag = 'replace-this-with-your-videoID';
document.write('<'+'script src="http://lckr.me/18B?s='+Math.round(Math.random()*100000)+'" type="text/javascript"><'+'/script>');
</script>

Related

Get the href value using HTML5 data attributes

I would like to get the value of the href i.e. the web link using the data attribute.
I have the following snippet of code
<div class="my-item-details">
<h3 class="my-item-title" data-item_item="x12">
<a href="http://link.com">
My Classic Box
</a>
</h3>
<span class="my-item-price" data-item_item="x12">
38.00
</span>
</div>
The following 2 snippets give the right output.
var price_val = $('.my-item-price[data-item_uuid=x12]').text();
price_val = $.trim(price_val)
console.log(price_val);
38.00
var item_name = $('.my-item-title[data-item_uuid=x12]').text();
item_name = $.trim(item_name)
console.log(item_name);
My Classic Box
However when I run this code
var item_link = $('.my-item-title[data-item_uuid=x12]').attr("href");
item_link = $.trim(item_link)
console.log(item_link);
I get an empty string instead of http://link.com
What am I missing?
.my-item-title[data-item_uuid=x12] selects the h3 element, which doesn't have an href attribute.
Only the a element has that.
Add a descendant combinator and a type selector:
.my-item-title[data-item_uuid=x12] a
You are trying to get the attribute href from a <h3> element without href property:
You could make a change on your selector this way to get the correct result:
var item_link = $('.my-item-title[data-item_uuid=x12] > a').attr("href");
This should give you the correct value.

Splitting an href and putting the html into a variable

I want to send this HTML, minus "/modal" into a variable:
<span class="detailsLink"><object>DETAILS</object></span>
How can I add to this line to make it work?:
var eemailDetails = $('.detailsLink').html();
This ends up taking out /modal before it passes it into the variable:
var eemailDetails = $('.detailsLink a').each(function(){
this.href = this.href.replace('/modal', '');
}).html();
Thank you for your time!
The replacement should be made on the value retrieved instead of on the element's attribute.
So to retrieve the HTML markup including the targeted element, the outerHTML property can be used.
// Get the whole HTML
var eemailDetails = $('.detailsLink')[0].outerHTML;
// Remove /modal
eemailDetails = eemailDetails.replace('/modal', '');
console.log("The attribute unchanged: "+$('.detailsLink a').attr("href"));
console.log("The HTML retrieved: "+eemailDetails);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object>DETAILS</object></span>
So the each works fine, and I save the variable as a data-attribute on the element itself. Later, when it gets clicked, I can recall that data attribute as needed. Hope this helps!
$('.detailsLink a').each(function(){
var changedLink = this.href.replace('/modal', '');
$(this).data("changedLink", changedLink)
});
$(".detailsLink a").on("click", function(event){
event.preventDefault();
var returnEl = $(this).parents(".detailsLink").clone();
returnEl.find("a").attr("href", $(this).data("changedLink") );
console.log(returnEl[0].outerHTML );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object>DETAILS</object></span>
<span class="detailsLink"><object>More DETAILS</object></span>
<span class="detailsLink"><object>Yet More DETAILS!</object></span>

Use button to setAttribute and display it within span tag

I am trying to create a real-world example of get and set data attribute.
so I created a simple div that contains the data-email attribute and set a default one.
Now what I want to attain is when I click on the button it will change the default attribute to the set attribute on my JavaScript codes.
Currently I also don't know how can I show the data attribute value inside tag of my div.
here's my markup:
<div id="my-id" data-email="youremail#email.com">Sam's email is <span> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click-btn()">Set Attribute Now</button>
here's my JavaScript:
var email = document.getElementById('my-id');
var emailget = email.getAttribute('data-email');
var button = document.getElementById('btn-id');
function click-btn(){
emailset = email.setAttribute('data-email', newemail#email.com);
}
here's the JSFIDDLE link: http://jsfiddle.net/jypb2jdg/6/
Any idea?
As #adeneo suggested we should not use hyphen in function name as it may be interpreted as minus sign, so remove and you may use like this:
You need to use quote in setAttribute value:
function clickBtn(){
emailset = email.setAttribute('data-email', 'newemail#email.com');
//^^ here ^^
}
You need something like this:
function clickBtn(){
emailset = email.setAttribute('data-email',
email.getAttribute('data-email') || 'newemail#email.com');
}
First thing is that the email you've written must be within quotes.
<div id="my-id" data-email="youremail#email.com">Sam's email is <span id="my-span-id"> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click_btn()">Set Attribute Now</button>
The JS code:
function click_btn(){
var email = document.getElementById('my-id');
var emailContainer = document.getElementById("my-span-id");
var emailget = email.getAttribute('data-email');
emailContainer.innerText = emailget;
emailset = email.setAttribute('data-email', "newemail#email.com");
}
The code can be found in:
http://jsfiddle.net/jypb2jdg/17/
Some point I want to mention:
Include the JS before the div. Because button will not recognize click_btn() function before its declaration;
Do not use '-' symbol for function names in JS.
You could write a script without using ID for span. It will need additional structs (finding child elements, figuring out which one is what you need, set its' innertext.
You need to keep in mind that functions in javascript cannot have hyphens in their name as it is treated as a mathematical operator. Rest is just plain DOM manipulation :
<div id='my-id' data-email="youremail#email.com">Sam's email is <span id="mail"> "Show Email Here" </span>
</div>
<button type="button" id="btn-id" onclick="clickbtn()">Set Attribute Now</button>
jS:
var em;
window.onload = function(){
em = document.getElementById("my-id");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
};
function clickbtn(){
var old_mail = em.getAttribute("data-email");
em.setAttribute("data-email","newmail");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
}
Fiddle : http://jsfiddle.net/dndnqygL/4/
Note : instead of assigning a new id to the span you can also use the element.firstChild property to set the innerHTML.

Javascript : format string and avoid multiple replace

I have the following string :
var str='
<span class="productName">Basa fillets</span><br>
Brand:
<span class="brandName">COMPLIMENTS</span><br>
400 <abbr title="Gram" lang="en">gr</abbr>
'
I need to get the '400' (could be a word,or even a sentence).
What I have so far is :
d = str.replace(/<br>/g,'').replace(/<.*<\/.*>/g,'').replace(/\n/g,'').replace(/ */g,'').replace(/brand:/i,'');
It works but... well, I'm sure I can do better. i have plenty of similar queued replace in my code, and I'd like to know how to improve that so i'm more looking for a general answer than a particular solution.
Thanks!
Instead of using string tools/regex on this, you can use DOM methods on it (it is HTML).
First you make a "fake" div and add the HTML to it.
var str="\
<span class=\"productName\">Basa fillets</span><br>\
Brand: \
<span class=\"brandName\">COMPLIMENTS</span><br>\
400 <abbr title=\"Gram\" lang=\"en\">gr</abbr>\
";
var fakeDiv = document.createElement('div');
fakeDiv.innerHTML = str;
Then just use normal DOM traversal methods to get the node you need. There are many ways to get to the element, depending on your HTML.
var brandName = fakeDiv.getElementsByClassName('brandName');
var textNode = brandName[0].nextSibling.nextSibling;
console.log(textNode.nodeValue.trim());
DEMO: http://jsfiddle.net/aqpgV/
Or, you can start from the <abbr> element and work backwards.
var gram = fakeDiv.getElementsByTagName('abbr');
var textNode = gram[0].previousSibling;
console.log(textNode.nodeValue.trim());
DEMO: http://jsfiddle.net/aqpgV/1/
However you traverse it is up to you :-)
Regex
class="brandName">[^<]+</span><br>[^\w]+([^<]+) <abbr title=
Debuggex Demo
Notes: Group 1 will contain the item you want.
If you wanted to use regex, you could do something like this.
var str="\
<span class=\"productName\">Basa fillets</span><br>\
Brand: \
<span class=\"brandName\">COMPLIMENTS</span><br>\
400 <abbr title=\"Gram\" lang=\"en\">gr</abbr>\
";
var myRegexp = /COMPLIMENTS<\/span><br>\W(.*?) <abbr /g;
var match = myRegexp.exec(str);
alert(match[1]);

javascript to replace all instances of a text within [] with hyperlinks

Am now facing an other challenge. Some parts of my html code has the following lines:
<div class="action-body flooded"><p>(In <span class="error">[82681]</span>) refs AGLBD-16096<br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
This is all what I have written till now with pimvdb's help:
<script type="text/javascript">
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
</script>
This JSFiddle does what you need: http://jsfiddle.net/TNyms/
When you replace getElementById('body') with document.body, the code works for me.
var body = document.body;
var link = "Pradeep";
body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link);
That replaces all IDs in this with links:
<div class="action-body flooded">
<p>(In
<span class="error">[82681]</span>) refs
AGLBD-16096
<br/>
</div>
<div>[123][abcd]</div>
<div>[456]</div>
<div>[789]</div>
Outputs:
(In Pradeep) refs AGLBD-16096
PradeepPradeep
Pradeep
Pradeep
Try it with this fiddle.
Your question appears to be related to what is asked in the below link. You may refer this
Replace number in a string using regex or something else

Categories

Resources