I have a string that might contain one or more instances of a YouTube or Vimeo anchors. I am looking for a javascript function that searches through this string, detects if the anchor href is youtube or Viemo url, and if so, then replaces the anchor with an iframe with the href value.
Note: This is a string that comes from an api, not a dom element. Before sending it to the view I want to make this switch.
Input:
"check out this video! <a href="https://www.youtube.com/watch?v=STsWJ63QgCg&ab_channel=BonApp%C3%A9tit">https://www.youtube.com/watch?v=STsWJ63QgCg&ab_channel=BonApp%C3%A9tit</a>"
And I want to change that anchor to an iframe instead so that you can just play the video instead of going to the link.
So something like this:
"check out this video! <iframe src=\"https://www.youtube.com/watch?v=STsWJ63QgCg&ab_channel=BonApp%C3%A9tit\" frameborder=\"0\" allowfullscreen=\"true\" allow=\"autoplay\"></iframe>";
Ive tried regex but Im not that good at it, and I havent found any good examples. This is basically what I have:
function checkForVideoUrl(message) {
var youtubeCheck = "<a href=\"https://www.youtube.com/watch";
var vimeoCheck = "https://vimeo.com/";
if (message.toLowerCase().toString().indexOf(youtubeCheck) !== -1 || message.toLowerCase().toString().indexOf(vimeoCheck) !== -1) {
console.log('true');
// Replace anchors with video href's to iframes
}
}
