Check if a JavaScript string is a URL

前端 未结 30 2914
野趣味
野趣味 2020-11-22 15:41

Is there a way in JavaScript to check if a string is a URL?

RegExes are excluded because the URL is most likely written like stackoverflow; that is to s

30条回答
  •  逝去的感伤
    2020-11-22 16:37

    The question asks a validation method for an url such as stackoverflow, without the protocol or any dot in the hostname. So, it's not a matter of validating url sintax, but checking if it's a valid url, by actually calling it.

    I tried several methods for knowing if the url true exists and is callable from within the browser, but did not find any way to test with javascript the response header of the call:

    • adding an anchor element is fine for firing the click() method.
    • making ajax call to the challenging url with 'GET' is fine, but has it's various limitations due to CORS policies and it is not the case of using ajax, for as the url maybe any outside my server's domain.
    • using the fetch API has a workaround similar to ajax.
    • other problem is that I have my server under https protocol and throws an exception when calling non secure urls.

    So, the best solution I can think of is getting some tool to perform CURL using javascript trying something like curl -I . Unfortunately I did not find any and in appereance it's not possible. I will appreciate any comments on this.

    But, in the end, I have a server running PHP and as I use Ajax for almost all my requests, I wrote a function on the server side to perform the curl request there and return to the browser.

    Regarding the single word url on the question 'stackoverflow' it will lead me to https://daniserver.com.ar/stackoverflow, where daniserver.com.ar is my own domain.

提交回复
热议问题