New method for validating URLs in JavaScipt (2023 version)

Since the birth of JavaScript, there has been no simple way to verify URLs. Now JavaScript has added a new method - URL.canParse .

URL.canParse('https://www.stefanjudis.com'); // true 
URL.canParse('www.stefanjudis.com'); // false

URL.canParse() is a quick way to verify that a string is a valid URL. However, we should not be too happy too early. The URL.canParse() method still has browser compatibility issues. At the time of writing this article, the browser version that supports this method is as follows:

Here is a link to detailed browser support information: https://caniuse.com/?search=canParse.

Howevercore-js already supports the URL.canParse() method. Using core-js as a shim can solve the problem of browsing Server compatibility issues.

URL.canParse()The and URL() constructors use the same algorithm to evaluate valid URLs.

Since both methods implement the same parser, andURL() is currently well supported, we can use the constructor to validate the URL. Put the newURL() in a helper function, call it and check if it throws an exception!

function isUrlValid(string) {
  try {
    new URL(string);
    return true;
  } catch (err) {
    return false;
  }
}

isUrlValid('https://www.stefanjudis.com'); // true
isUrlValid('www.stefanjudis.com'); // false

If you don’t like the isUrlValid function, you can also polyfill it like core-js URL.canParse() .

Follow the official account [Programmer Ling Lan] and reply "666", which will bring you into the [Human high-quality front-end communication group~]
Past recommendations: linglan01.cn/about

Guess you like

Origin blog.csdn.net/qq_45472813/article/details/134994266