Madao Madao - 5 months ago 17
Javascript Question

Replacing youtube URLs using regex carriage return converted to <br></br>

I'm trying to replace YouTube links on my webpages using JavaScript. This regex finds the videos that are separated by spaces, but not carriage returns. Carriage returns are converted into

<br>
on my site.



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);
}
}
}

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





Any help getting this to find all the links?

Answer

Use:

/http(s)?:\/\/www\.youtube\.com\/watch\?v=([^\\\. <>]+)/ig

It's a simpler version of yours, which uses the optional item (s)? (click here for info) to include http and https. I kept everything else the same and it works on all of them, thanks to the /g flag.

In your http:// links, you also have an invisible Unicode character that stops the regex from matching. Rewrite your youtube links to remove the character and you'll see it matches.

Additionally, I've removed the multi-line flag /m as it wasn't necessary for your example. /i can also be removed for your example.

You can see it in action here:

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);
        }
    }
}
<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.youtube.com/watch?v=Ui1sHwYp_Ys http://www.youtube.com/watch?v=Ui1sHwYp_Ys<br><br>0.00020694732666016
</div>

Comments