JavaScript Regex to match a URL in a field of text

前端 未结 8 1258
一向
一向 2020-12-01 02:01

How can I setup my regex to test to see if a URL is contained in a block of text in javascript. I cant quite figure out the pattern to use to accomplish this



        
相关标签:
8条回答
  • 2020-12-01 02:55

    You have to escape the backslash when you are using new RegExp.

    Also you can put the dash - at the end of character class to avoid escaping it.

    & inside a character class means & or a or m or p or ; , you just need to put & and ; , a, m and p are already match by \w.

    So, your regex becomes:

    var urlexp = new RegExp( '(http|ftp|https)://[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?' );
    
    0 讨论(0)
  • 2020-12-01 02:56

    I've cleaned up your regex:

    var urlexp = new RegExp('(http|ftp|https)://[a-z0-9\-_]+(\.[a-z0-9\-_]+)+([a-z0-9\-\.,@\?^=%&;:/~\+#]*[a-z0-9\-@\?^=%&;/~\+#])?', 'i');
    

    Tested and works just fine ;)

    0 讨论(0)
提交回复
热议问题