使用正则表达式回车符替换youtube URL转换为<br/> <br/>

时间:2016-06-23 17:31:25

标签: javascript

我尝试使用JavaScript替换网页上的YouTube链接。此正则表达式查找由空格分隔的视频,但不包括回车符。回车在我的网站上转换为<br>

&#13;
&#13;
findReplaceYoutube();

function findReplaceYoutube() {
    var youregx = /[^<br>]https:\/\/www\.youtube\.com\/watch\?v=([^//\\\. <>]+)|[^<br>]http:\/\/www\.youtube\.com\/watch\?v=([^//\\\. <>]+)/igm;
    var content = document.getElementsByClassName("new_thread_message_preview");
    var contentsize = content.length;
    var match;
    
    for (var i = 0; i < contentsize; i++) {
        match = youregx.exec(content[i].innerHTML);
        while (match != null) {
            alert(match[0]);
            match = youregx.exec(content[i].innerHTML);
        }
    }
}
&#13;
<div class="new_thread_message_preview">
https://www.youtube.com/watch?v=Ui1sHwYp_Ys https://www.youtube.com/watch?v=Ui1sHwYp_Ys<br>
http://www.yout­ube.com/watch?v=Ui1sHwYp_Ys­ http://www.youtube.com/watch?v=Ui1sHwYp_Ys<br><br>0.00020694732666016
</div>
&#13;
&#13;
&#13;

有什么帮助可以找到所有链接吗?

1 个答案:

答案 0 :(得分:2)

使用:

F(v1+v2)=F(v1)+F(v2)  Additivity <= should apply better in your case
y ( x , t ) = y m sin ( k 1 x - w1 t ) + y m sin ( k 2 x + w 2 t ) 

w1 = velocity component 1
w2 = velocity component 2
x = phase 

这是您的更简单版本,它使用可选项(s)? (click here for info)来包含 http https 。由于/ g标志,我保持其他所有内容都相同并且适用于所有这些。

在http://链接中,您还有一个不可见的Unicode字符,可以阻止正则表达式进行匹配。重写你的youtube链接以删除该角色,你会看到它匹配。

此外,我删除了多行标记/http(s)?:\/\/www\.youtube\.com\/watch\?v=([^\\\. <>]+)/ig ,因为您的示例不需要。您的示例也可以删除/m

你可以在这里看到它:

/i
findReplaceYoutube();

function findReplaceYoutube() {
    var youregx = /http(s)?:\/\/www\.youtube\.com\/watch\?v=([^\\\. <>]+)/ig;
    var content = document.getElementsByClassName("new_thread_message_preview");
    var contentsize = content.length;
    var match;
    
    for (let i = 0; i < contentsize; i++) {
        match = youregx.exec(content[i].innerHTML);
      
        while (match != null) {
            alert(match[0]);
            match = youregx.exec(content[i].innerHTML);
        }
    }
}

相关问题