开发者

parse multiple youtube links to objects or iframes using regex in javascript

I want to parse multiple youtube links to embedded objects in a text.

For example, in the text:

This is a test another testing I'm writing this...
http://www.youtube.com/watch?v=-LiPMxFBLZY This is a test another testing I'm writing this...
http://www.youtube.com/watch?v=Q3-l22b_Qg8&feature=related another test

Now, the links are to be converted to iframes, and the resulting text would be:

This is a test another testing I'm writing this...
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="425" height="350" src="http://www.youtube.com/embed/-LiPMxFBLZY" frameborder="0"> </iframe> Thi开发者_如何学Gos is a test another testing i m writing this...
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="425" height="350" src="http://www.youtube.com/embed/Q3-l22b_Qg8" frameborder="0"></iframe> another test

The text then has to be sent to linkify any other links using this code...

function text_to_link(inputText) {
    var object_text = new Array();
    var oi = 0;

    while (inputText.indexOf('<object') >= 0) {
        var si = inputText.indexOf('<object');
        var ei = inputText.indexOf('</object>');
        object_text[oi] = inputText.substring(si, ei + 9);

        inputText = inputText.replace(object_text[oi], '[ob_service]');
        oi++;
    }

    var iframe_text = new Array();
    var ii = 0;
    while (inputText.indexOf('<iframe') >= 0) {
        var si = inputText.indexOf('<iframe');
        var ei = inputText.indexOf('</iframe>');
        iframe_text[ii] = inputText.substring(si, ei + 9);

        inputText = inputText.replace(iframe_text[ii], '[if_service]');
        ii++;
    }

    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    inputText = inputText.replace(exp, "<a href='$1' target='_blank'>$1</a>");

    oi = 0;
    while (inputText.indexOf('[ob_service]') >= 0) {
        inputText = inputText.replace('[ob_service]', object_text[oi]);
        oi++;
    }

    ii = 0;
    while (inputText.indexOf('[if_service]') >= 0) {
        inputText = inputText.replace('[if_service]', iframe_text[ii]);
        ii++;
    }

    return inputText;

}

Please help me find a more simple regex solution...


Basically, you want to match a link that start either with 'http,https, file or file'. But you don't want to match links that may appear inside iframe or object tags or as attributes of these two previous tags.

Unfortunately, you have hit a limit of Javascript regular expressions. For solving your problem you need a good html parser.

BTW, you could refactor your code. The loops before and after the link replacement could be placed in functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜