I want to parse "string" and search "url" of various types like
"href", "image", "youtube", "vimeo", "hashtag", "mention" with #
and convert them into "HREF" as well as other formats like iframe, "img" when available.
Following is my code, which is not working as it is supposed to be:
function convertLink(article) {
var cArticle = "";
cArticle = article.replace(/(?:(https?):\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^\ \r\n]+)/g, '<div id="$2" class="anotherClass" onclick="someFunction(\'$2\', \'$2\');"><img class="some-class" src="https://i.ytimg.com/vi/$2/0.jpg"></div>')
.replace(/(?:(https?):\/\/)?(?:www\.)?(?:vimeo\.com)\/([^\ \r\n]+)/g, '<div class="video-container"><iframe src="//player.vimeo.com/video/$2" width="100%" height="480" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>')
.replace(/([\s+])#([^\s]+)/g, " <a href='https:\/\/example.com/$2'>#$2</a>").replace(/([\r\n])/ig, "<br>")
.replace(/([\s+])#([^\s]+)/g, " <a href='https:\/\/example.com/#2'>#$2</a>").replace(/([\r\n])/ig, "<br>")
.replace(/(\<br\>\<br\>)/, "<br>");
return cArticle;
}
It only converts youtube link and ignores other following links.
Example of String:-
In this article, we will be talking about Some of the interesting facts like:
Youtube Flutter https://youtube.com/watch?v=someVideoID as well as https://example.com/images.jpg, https://vimeo.com/someVideoID and #rain #stackoverflow more coming soon at https://example.com/link/me Let's talk.
To get Converted to semi-html as below:-
In this article, we will be talking about some of the interesting facts like: <span class="someClass" onclick="someFunction(videoID)"><img src="https://.ytimg.com/vi/{vidoeID}/0.jpg"></span> as well as <img class="imgClass" src="https://example.com/images.jpg" /> , <div class="video-container"><iframe src="//player.vimeo.com/video/"></iframe></div> and #rain #stackoverflow and more coming soon at https://example.com/link/me
So, if you see -
https://example.com/images.jpg => becomes => <img class="imgClass" src="https://example.com/images.jpg" />
https://youtube.com/watch?v=someVideoID => becomes => <span class="someClass" onclick="someFunction(videoID)"><img src="https://.ytimg.com/vi/{vidoeID}/0.jpg"></span>
#rain => becomes => #rain
#stackoverflow => becomes => #stackoverflow
https://example.com/link/me => becomes => https://example.com/link/me
image text link, youtube, Vimeo, and text link is converted to img, iframe and HTML link
JsFiddle link here for Live Testing - https://jsfiddle.net/thadg3uf/
function convertLink(article) {
var cArticle = "";
cArticle = article.replace(/(?:(https?):\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^\ \r\n]+)/g, '<div id="$2" class="anotherClass" onclick="someFunction(\'$2\', \'$2\');"><img class="some-class" src="https://i.ytimg.com/vi/$2/0.jpg"></div>').replace(/(?:(https?):\/\/)?(?:www\.)?(?:vimeo\.com)\/([^\ \r\n]+)/g, '<div class="video-container"><iframe src="//player.vimeo.com/video/$2" width="100%" height="480" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>').replace(/([\s+])#([^\s]+)/g, " <a href='https:\/\/example.com/$2'>#$2</a>").replace(/([\r\n])/ig, "<br>").replace(/([\s+])#([^\s]+)/g, " <a href='https:\/\/example.com/#2'>#$2</a>").replace(/([\r\n])/ig, "<br>").replace(/(\<br\>\<br\>)/, "<br>");
return cArticle;
}
var stringIs = "In this article, we will be talking about Some of the interesting facts like: Youtube Flutterhttps://www.youtube.com/watch?v=i-Qy1VQUMuI as well as https://example.com/images.jpg, https://vimeo.com/259411563 and #rain #stackoverflow more coming soon at https://example.com/link/me Let's talk.";
document.getElementById("demo").innerHTML = convertLink(stringIs);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Convert Link</title>
</head>
<body>
<span id="demo"></span>
</body>
</html>
Strictly No jQuery with XSS filter to avoid any XSS attack
I believe this is the change you are looking for, What I did here (the snippet below) over what is your code doing. I add two replace statements,
searched for all URLs and replaced them with links, this is to make sure that I don't override the other patterns we are replacing.
searched for all href links with images extensions (I didn't add all image ext, you can add more as fits for your app) and replaced the whole tag with tag, I hope this help.
Update: Add XSS, in case your input is simple you can use a custom function to match patterns from XXS OWASP XSS prevention sheet the only thing that didn't work for me is the '/' which I had to whitelist it, otherwise I really suggest to a library to js-xss or DOMPurify to filter XSS potential text in your data input.
function sanitizeString(str) {
// "/": '/',
const patterns = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"`": '`'
};
const reg = /[&<>"']/ig;
return str.replace(reg, (match)=>(patterns[match]));
}
function convertLink(article) {
let cArticle = "";
cArticle = article
.replace(/(\bhttps?:\/\/\S+)/g, 'linked tag')
.replace(/<a href="((?:(https?):\/\/)([^\s]+)(\.(jpg|jpeg|gif|png))).">([\s\S]*?)<\/a>/g, '<img width="200" height="100" src="$1" />')
.replace(/(?:(https?):\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^\ \r\n]+)/g, '<div id="$2" class="anotherClass" onclick="someFunction(\'$2\', \'$2\');"><img class="some-class" src="https://i.ytimg.com/vi/$2/0.jpg"></div>')
.replace(/<a href="(?:(https?):\/\/)?(?:www\.)?(?:vimeo\.com)\/([^\ \r\n]+)">([\s\S]*?)<\/a>/g, '<div class="video-container"><iframe src="//player.vimeo.com/video/$2" width="100%" height="480" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>')
.replace(/([\s+])#([^\s]+)/g, " <a href='https:\/\/example.com/$2'>#$2</a>")
.replace(/([\r\n])/ig, "<br>")
.replace(/([\s+])#([^\s]+)/g, " <a href='https:\/\/example.com/#2'>#$2</a>")
.replace(/([\r\n])/ig, "<br>")
.replace(/(\<br\>\<br\>)/, "<br>");
return cArticle;
}
let stringIs = "In this article, we will be talking about Some of the interesting facts like: Youtube Flutterhttps://www.youtube.com/watch?v=i-Qy1VQUMuI as well as https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg, https://vimeo.com/259411563 and #rain #stackoverflow more coming soon at https://example.com/link/me Let's talk. here is XSS sample <div>Testing xss</div>";
stringIs = sanitizeString(stringIs);
document.getElementById("demo").innerHTML = convertLink(stringIs);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Convert Link</title>
</head>
<body>
<span id="demo"></span>
</body>
</html>
You already have most of the things working for you, except "link", "hashtag" and "mention", for that I will recommend using - linkify ( https://soapbox.github.io/linkifyjs/docs/2.1.html )
It will solve your remaining part excluding the "image" tag.
For Image tag, you can use something like this, when the link is already converted to a tag:
jQuery('a[href$=".png"], a[href$=".jpg"], a[href$=".gif]"').each(function(){
jQuery(this).html('<img src="' + jQuery(this).attr('href') + '" />');
});
I use URL's like: http://example.com/videos/GF60Iuh643I
I'm trying to use javascript inside iframe to embed youtube videos:
<iframe width="560" height="315" src="https://www.youtube.com/embed/<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment);
</script>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
It should give src="https://www.youtube.com/embed/GF60Iuh643I"
But instead the javascript remains unexecuted,
any idea how to make this work?
Thank you!
Try this(not tested). You get the iframe by id and then set the src to equal the link + the last segment.
<iframe id="videoframe" width="560" height="315" src="" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.getElementById('videoframe').src = 'https://www.youtube.com/embed/' + last_segment;
</script>
I have a string like this
var string = '<img src="test.jpg'><img src="test2.jpg>';
var dom = new JSDOM(string,{ includeNodeLocations: true });
dom = dom.window.document.querySelectorAll("img");
for(var i = 0;i< dom.length;i++) {
text = string.replace(/<img[^>]*>/g,'<amp-img layout="responsive" class="ampimageheight" src="'+dom[i].getAttribute('src')+'" width="200" height= "100"></amp-img>');
}
But my output is
<amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img><amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img>
In which only the second image src is replaced for 2 imags.I think this is because of the asynchronous.Can anyone please help me.Thanks.
Well, if you run replace in a loop, you don't need set the Regex's flag.
Because that replace all img when first time loop.
After first loop is do nothing.
So, you can remove Regex flag, or use a callback replace your function's second arguments, like this.
text = string.replace(/<img[^>]*>/g, function(str, index){
return '<amp-img layout="responsive" class="ampimageheight" src="'+dom[index].getAttribute('src')+'" width="200" height= "100"></amp-img>'
});
And it doesn't need loop;
I'm hoping the above title is accurate to what I need to do. I've been Googling my face off and nothing seems to be working.
Here is a snippet of my code...
var options = {
campaigns: {
'hydraulic_repair': {
phone: '(555) 555-5555',
myform: '<div class="adwords-switched"><iframe src="http://www.mywebsite.com/contact-form-google-sfp/" allowtransparency="true" width="100%" height="725px" type="text/html" scrolling="no" frameborder="0" style="border:0"></iframe></div>'
}
}
};
I now need to add some variables into the mix. It works fine when I hard code the variables like this:
http://www.mywebsite.com/contact-form-google-sfp/?keyword=HELLO&adgroup=WORLD
however the keyword and adgroup are going to be dynamic, and when I try to enter variables into the string, it breaks my code. I'm not sure why the "+" concatenation isn't working, is there a different method to add variables in that I'm missing?
var mykeyword = 'HELLO';
var myadgroup = 'WORLD';
var options = {
campaigns: {
'hydraulic_repair': {
phone: '(555) 555-5555',
myform: '<div class="adwords-switched"><iframe src="http://www.mywebsite.com/contact-form-google-sfp/?keyword='+mykeyword+'&adgroup='+myadgroup+'" allowtransparency="true" width="100%" height="725px" type="text/html" scrolling="no" frameborder="0" style="border:0"></iframe></div>'
}
}
};
How can I get the value of flashvars attribute?
<embed src="http://wl2static.lsl.com/common/flash/as3/MemberApplet026.swf"
id="opera_elb" width="100%"
height="100%"
allowscriptaccess="always"
allowfullscreen="true"
bgcolor="ffe8ef"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
flashvars="muteaudio=0&ishd=1&ishq=0&twoway=0&proxyip=">
I am using getElementsByTagName to get the element.
var Em = content.document.getElementsByTagName('embed');
And replace values in flashvars
<script>
function myFunction()
{
var Em = content.document.getElementsByTagName('embed');
var str = Em[0].getAttribute('flashvars').innerHTML;
var res = str.replace("muteaudio=0","muteaudio=1");
document.getElementsByTagName("embed").innerHTML=res;
}
</script>
But when I try error: Uncaught ReferenceError: content is not defined
please help me.
Okay so here is a solution (strictly to change the attribute of flashvars!). First I think you have a few syntax errors within your JS. So I modified it and here is the JS:
function myFunction()
{
var Em = document.getElementById('vid');
var str = Em.getAttribute('flashvars');
var contentSpot = document.getElementById("he");
contentSpot.innerHTML = Em.getAttribute('flashvars');
Em.setAttribute('flashvars', 'muteaudio=1')
// contentSpot.innerHTML = Em.getAttribute('flashvars');/* I used this to see if the change occurred.*/
}
window.onload = myFunction();
So contentSpot is a div element I created to observe the change.
the html is here:
<embed id="vid" src="http://wl2static.lsl.com/common/flash/as3/MemberApplet026.swf"
id="opera_elb" width="100%"
height="100%"
allowscriptaccess="always"
allowfullscreen="true"
bgcolor="ffe8ef"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
flashvars="muteaudio=0&ishd=1&ishq=0&twoway=0&proxyip=">
<div id="he"> Hello</div> <!-- The created div to observe -->
Okay so here is my suggestion:
1)pop in the cleaned up code into a jsfiddle, then observe the content.
2)Then remove the line: contentSpot.innerHTML = Em.getAttribute('flashvars'); above the code: Em.setAttribute('flashvars', 'muteaudio=1').
3) remove comments slashes and then hit ctrl + enter to observe the attribute change.
*really watch your "."/DOM syntax and case sensitivity.
Hope this helps you out!