regex to find url in a text

前端 未结 6 464
星月不相逢
星月不相逢 2020-11-28 14:19

I have to find the first url in the text with a regular expression:

for example:

I love this website:http://www.youtube.com/music it\'s fantastic
         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 14:40

    Identifying URLs is tricky because they are often surrounded by punctuation marks and because users frequently do not use the full form of the URL. Many JavaScript functions exist for replacing URLs with hyperlinks, but I was unable to find one that works as well as the urlize filter in the Python-based web framework Django. I therefore ported Django's urlize function to JavaScript: https://github.com/ljosa/urlize.js

    It actually would not pick up the URL in your example because there is a colon right before the URL. But if we modify the example a little:

    urlize("I love this website: http://www.youtube.com/music it's fantastic", true, true)
    => 'I love this website: http://www.youtube.com/music it's fantastic"'
    

    Note the second argument which, if true, inserts rel="nofollow" and the third argument which, if true, quotes characters that have special meaning in HTML.

提交回复
热议问题