You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于输入的URL验证:强制统一HTTPS并优化链接显示

解决方案

要实现你要求的两个效果,我们可以给输入的URL做两步处理:提取不带协议的纯域名作为链接显示文本,同时强制给跳转链接加上HTTPS前缀。修改后的代码如下:

JavaScript 代码

$('#website-url').keyup(function() {
  let inputUrl = this.value.trim();
  if (!inputUrl) {
    $('.website_url').html('[WEBSITE URL]');
    $('.website_url').prop('href', '#');
    return;
  }
  
  // 提取不带http/https前缀的域名作为显示文本
  let displayText = inputUrl.replace(/^(https?:\/\/)?(www\.)?/, '$2').replace(/\/.*$/, '');
  // 确保链接以https://开头
  let httpsUrl = inputUrl.replace(/^(https?:\/\/)?/, 'https://');
  
  $('.website_url').html(displayText);
  $('.website_url').prop('href', httpsUrl);
});

HTML 代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="website-url" class="small mb-0">Website URL ✱</label>
<br>
<input class="form-control text-dark form-control-sm px-1 border-bottom border-success border-1 m-0 mb-2" type="url" id="website-url" placeholder="websiteurl.com" aria-label="Website URL" required>
<br>
Welcome to our website: <a href="#" class="website_url">[WEBSITE URL]</a>.
<br>
Please do not continue to use <a href="#" class="website_url">[WEBSITE URL]</a> if you do not agree with all of the terms and conditions stated on this page.

代码说明

  • 增加了空值处理:输入为空时恢复默认的提示文本与占位链接
  • 用正则剥离URL开头的http://或https://前缀,保留www.(如果存在),同时去掉域名后的路径部分,确保显示的是纯域名格式
  • 强制将所有跳转链接替换为https://开头,不管输入的原链接是否带协议、带的是HTTP还是HTTPS
  • 修正了HTML中input标签的requiered拼写错误,改为正确的required

内容的提问来源于stack exchange,提问作者kkoss asa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:26:16