Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all instances of video anchors to iframes

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>"

homepage view: enter image description here

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
}

}

like image 678
swedish_junior_dev Avatar asked Dec 31 '25 07:12

swedish_junior_dev


1 Answers

Using regex to amend HTML is not good practice. Use a library which can parse a string to a DOM structure and amend it there. As you've tagged the question with jQuery, you can use that in this instance.

The following example finds all a elements within the string and replaces them with an iframe whose src is set to the same value as the original href. Try this:

var 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>';

let $input = $(`<div>${input}</div>`);
let $a = $input.find('a');
$a.replaceWith(i => `<iframe src="${$a.eq(i).prop('href')}" frameborder="0" allowfullscreen="true" allow="autoplay"></iframe>`);

console.log($input.html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
like image 65
Rory McCrossan Avatar answered Jan 03 '26 04:01

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!