[JS] Method to determine whether a string is a url

Article directory

Usage analysis

When you pass a string to the URL constructor:

  • If the string is a valid URL, it returns a new URL object.
  • Otherwise, it returns an error.
const url = new URL("https://www.baidu.com/");
console.log(url);

Insert image description here

  • Function encapsulation:
function isUrl(string){
    
    
  try {
    
    
    new URL(string);
    return true;
  } catch (err) {
    
    
    return false;
  }
}
  • Use Cases:
console.log(isUrl('https://www.baidu.com/'));	// true
console.log(isUrl('www.baidu.com'));	// false

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/134286443