我要自动修改的HTML看起来类似于以下内容:
<div class="blob-of-text">
<div>
Text
<br>
<br>
<a href="https://youtu.be/NTT1iNQq123" class="linkified" target="_blank">https://youtu.be/NTT1iNQq123</a>
<br>
<br>
https://youtu.be/NTT1iNQq123
</div>
</div>
我正在运行以下代码,这些代码已在各个位置找到并进行了修改,以更改我的html
html_data = $('.blob-of-text').html()
var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)$/g;
var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)$/g;
var pattern3 = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))$/gi;
if(pattern1.test(html_data)){
console.log("pattern 1");
var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
var html_data = html_data.replace(pattern1, replacement);
}
if(pattern2.test(html_data)){
console.log("pattern 2");
var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
var html_data = html_data.replace(pattern2, replacement);
}
if(pattern3.test(html_data)){
console.log("pattern 2");
var replacement = '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />';
var html_data = html_data.replace(pattern3, replacement);
}
$('.blob-of-text').html(html_data)
但是,它没有转换锚链接,由于某种原因,它使第一个iframe的链接包含了所有其余的html ...
可以看到一个很好的例子:https://jsfiddle.net/cupnabm7/6/