从锚标记中删除默认的 url

Remove the default url from anchor tag

我有以下代码,它从用户输入 link 并使用 href = link

创建一个 anchor 标签

<html>
<head>
    <title>Page Title</title>
    <style>
        #text-input {
            border-left: 4px solid green;
            text-indent: 12px;
        }
    </style>
</head>
<body>
    <p>Enter a link</p>
    <div id="text-input" contenteditable="true"></div>
    
    <script>
      let div = document.getElementById('text-input');
      let anchor;

      div.addEventListener('blur', event => {
        let text = div.innerText;
        div.innerText = '';
        anchor = document.createElement('a');
        div.appendChild(anchor);
        anchor.innerText = text;
        anchor.href = text;
        
        // The below line logs the actual link of the anchor tag
        console.log(anchor.href);
      });
    </script>
</body>
</html>

问题

当我将 link 的值赋给 href 时,似乎 link 也包含一些默认网站 url。我不想要那些默认的 urls。我该怎么办?

可能是相对 URL 的问题?如果正文没有,请在正文开头添加"http://"。

根据您的默认要求,您可以将 https 或 http 附加到输入数据。

 anchor.innerText = text;       
            if(text.indexOf('http://')!=0 || text.indexOf('https://')!=0){
                text = "http://"+text;  //default http(or) https
            }
             anchor.href = text;

您可能需要在开头添加 http:// 或 https://。

<html>
<head>
    <title>Page Title</title>
    <style>
        #text-input {
            border-left: 4px solid green;
            text-indent: 12px;
        }
    </style>
</head>
<body>
    <p>Enter a link</p>
    <div id="text-input" contenteditable="true"></div>
    
    <script>
      let div = document.getElementById('text-input');
      let anchor;

      div.addEventListener('blur', event => {
        let text = div.innerText;
        div.innerText = '';
        anchor = document.createElement('a');
        div.appendChild(anchor);
        anchor.innerText = text;
        anchor.href = 'http://'+text;
        
        // The below line logs the actual link of the anchor tag
        console.log(anchor.href);
      });
    </script>
</body>
</html>