Adding http:// to all links without a protocol

前端 未结 4 1342
鱼传尺愫
鱼传尺愫 2021-01-21 02:28

I use VB.NET and would like to add http:// to all links that doesn\'t already start with http://, https://, ftp:// and so on.

\"I want to add http h         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 02:45

    If you aren't concerned with potentially messing up local links, and you can always guarantee that the strings will be fully qualified domain names, then you can simply use the contains method:

    Dim myUrl as string = "someUrlString".ToLower()
    
    If Not myUrl.Contains("http://") AndAlso Not myUrl.Contains("https://") AndAlso Not myUrl.Contains("ftp://") Then
    
        'Execute your logic to prepend the proper protocol
        myUrl = "http://" & myUrl
    
    End If
    

    Keep in mind this omits a lot of holes regarding the checking of which protocol should be used in the addition and if the url is relative or not.

    Edit: I chose specifically not to offer a RegEx solution since this is a simple check and RegEx is a little heavy for it (IMO).

提交回复
热议问题