Javascript to get youtube video id (regex issue) - javascript

I use:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var field1 = document.getElementById("field_wy4dm0");
field1.addEventListener("change", combineFields);
function combineFields() {
var val1 = field1.value;
var val1re = val1.match("/(.*)?")[1];
var str = document.getElementById("changeThisMovie").innerHTML;
var res = str.replace("yeC3AisTs2Y", val1re);
document.getElementById("changeThisMovie").innerHTML = res;
}
});
</script>
It works great to get a youtube video id which is located between "/" and "?" in the "val1" var and replace the old video id "yeC3AisTs2Y" that is located inside a div with the id="changeThisMovie" with the new one ("val1re").
The problem is it adds "?" in the end of the new video id so instead of getting:
/videoid?feature=embed...
I get:
/videoid??feature=embed...
How do i fix this?
Thanks!!!

I think you want to escape the ? In your regex to mean the literal ? symbol - regex will interpret as ignore previous block
So you could try as follows:
var val1re = val1.match("/(.*)\?")[1];

Related

jQuery using Regex to find links within text but exclude if the link is in quotes

I am using jQuery and Regex to search a text string for http or https and convert the string to a URL. I need the code to skip the string if it starts with a quote.
below is my code:
// Get the content
var str = jQuery(this).html();
// Set the regex string
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '' + clean_url + '';
})
jQuery(this).html(replaced_text);
Here is an example of my issue:
Text The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter #Abcdef.
The current code successfully finds the text that starts with http or https and converts it to a URL but it also converts the twitter URL. I need to ignore the text if it starts with a quote or is within an a tag, etc...
Any help is much appreciated
What about adding [^"'] to the exp variable?
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
Snippet:
// Get the content
var str = jQuery("#text2replace").html();
// Set the regex string
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '' + clean_url + '';
})
jQuery("#text2replace").html(replaced_text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text2replace">
The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter #Abcdef.
</div>
If you really just want to ignore the quotation marks, this could help:
var replaced_text = $("#selector").html().replace(/([^"])(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig, '$1$2');
This works for me:
This will recognize urls and convert them to hyperlinks, but will ignore urls, wrapped in " (quotes).
See the code below or this jsfiddle for a working example.
Example HTML:
<ul class="js-replaceUrls">
<li>
www.link-only-www.com
</li>
<li>
http://link-starts-with-HTTP.com
</li>
<li>
https://www.link-starts-with-https-and-www.com
</li>
<a href="https://link-starts-with-https.com">
Link in anchor tag
</a>
</ul>
RegEX:
/(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:#/?]*)?)(\s+|$)/gmi
jQuery:
// RECOGNIZE URLS AND CONVERT THEM TO HYPERLINKS
// Ignore if hyperlink is found in HTML attr, like "href"
$('.js-replaceUrls').each(function(){
// GET THE CONTENT
var str = $(this).html();
// SET THE REGEX STRING
var regex = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:#/?]*)?)(\s+|$)/gmi;
// REPLACE PLAIN TEXT LINKS BY HYPERLINKS
var replaced_text = str.replace(regex, "<a href='$1' class='js-link'>$1</a>");
// ECHO LINK
$(this).html(replaced_text);
});
// DEFINE URLS WITHOUT "http" OR "https"
var linkHasNoHttp = $(".js-link:not([href*=http],[href*=https])");
// ADD "http://" TO "href"
$(linkHasNoHttp).each(function() {
var linkHref = $(this).attr("href");
$(this).attr("href" , "http://" + linkHref);
});
See this jsfiddle for a working example.

How to strip specific tag into div in Javascript?

I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here

Use a JavaScript variable as part of a href link in HTML

Part of my code:
<p id="demo">{$value.file_name}</p>
<script type="text/javascript">
var str = document.getElementById("demo").innerHTML;
var res = str.replace("/var/www/html/biology/demo", "");
document.getElementById('para').innerHTML = res;
</script>
<a href="#para" id='para'>Download</a>
This part of the url will already be present: "a.b.c.d.edu/bio/cluster/"
$value.file_name contains "/var/www/html/biology/demo/files/mpijobs/107/mothership/data/job107_0_0_output.tif"
After the script, "para" contains the edited path which is "/files/mpijobs/107/mothership/data/job107_0_0_output.tif" (the removal of "/var/www/html/biology/demo")
The code:
Download
provides a clickable link to "a.b.c.d.edu/bio/cluster//var/www/html/biology/demo/files/mpijobs/107/mothership/data/job107_0_0_output.tif"
and what I want to do is replace "{$value.file_name}" inside the brackets with "para" (and what it represents) so that the download link is linked to
"a.b.c.d.edu/bio/cluster//files/mpijobs/107/mothership/data/job107_0_0_output.tif"
Sorry, I misunderstood.
If the a href attribute is set like so:
Download
You can use in the javascript:
str.setAttribute("href", res);
EDIT:
Ok I got it. Sorry about this strenuous exercise. Here's what you should write:
<p id="demo">{$value.file_name}</p>
<a href="#para" id='para'>Download</a>
<script type="text/javascript">
var str = document.getElementById("demo").innerHTML;
var res = str.replace("/var/www/html/biology/demo", "");
para = document.getElementById('para');
para.href = res;
</script>

Extracting the source code of a facebook page with JavaScript

If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)

Get source of image

I have a next string like:
<img src="../uplolad/commission/ranks/avatar.jpg' . $row[$c_name] .'" width="50" height="50"/>
How can i get a image file name in javascript? I know only PHP regexes. Extention of a file can be different.
The result must be: avatar.jpg
Regex is not ideal for this. JavaScript can traverse the HTML as distinct objects more readily than as a long string. If you can identify the picture by anything, say by adding an ID to it, or an ID to a parent with that as the only image, you'll be able to access the image from script:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
var src = myImage.src; // will contain the full path
if(src.indexOf('/') >= 0) {
src = src.substring(src.lastIndexOf('/')+1);
}
alert(src);
And if you want to edit, you can do that just as well
myImage.src = src.replace('.jpg', '.gif');
Fetch it following coding which can help what you want to get.
<script type="text/javascript">
function getImageName(imagePath) {
var objImage = new RegExp(/([^\/\\]+)$/);
var getImgName = objImage.exec(imagePath);
if (getImgName == null) {
return null;
}
else {
return getImgName[0];
}
}
</script>
<script>
var mystring = getImageName("http://www.mypapge.mm/myimage.png")
alert(mystring)
</script>
Here's a shorter variation of David Hedlund's answer that does use regex:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
alert(myImage.src.replace( /^.+\// , '' ));

Categories