js——judging whether it is a link format

JavaScript cannot directly determine whether an attribute is a link, but it can preliminarily determine whether the attribute is a link by checking whether the value of the attribute conforms to the format of the link.

Usually, the URL address of the link starts with http:// or https://, so we can use regular expressions to match whether the value of this attribute conforms to this format. For example:

copy code

let myObj = {
    
     link: 'http://example.com' };

if (/^https?:\/\//.test(myObj.link)) {
    
    
  console.log('属性值是一个链接');
} else {
    
    
  console.log('属性值不是一个链接');
}

In this example, /^https?:\/\//is a regular expression that matches strings starting with http:// or https://. Then use the test() method to match the value of the myObj.link attribute. If the match is successful, it means that the value of the attribute is a link, otherwise it means it is not a link. It should be noted that information such as paths, parameters, etc. should also be considered when checking links.

Of course, if you want to make more accurate judgments on links in JavaScript, it is recommended to use a third-party library (such as URLParse.js or js-url) instead of manually writing regular expressions to parse links.

Guess you like

Origin blog.csdn.net/xulihua_75/article/details/130710749