首页 > 解决方案 > 如何从页面上的 URL 中删除 http(s)?

问题描述

我正在动态地将我的 CMS 中的 URL 拉入页面以成为页面内容的一部分,但我想通过使用 javascript 来显示它而不显示 http://(或 https://)部分。

基本上我想要这个:

在此处输入图像描述

在页面上呈现为:

在此处输入图像描述

请看我的 HTML:

<div class="elementor-element elementor-element-0e4572c elementor-widget elementor-widget-heading" data-id="0e4572c" data-element_type="widget" id="partner-website-element" data-widget_type="heading.default">
  <div class="elementor-widget-container">
    <h5 class="elementor-heading-title elementor-size-default">
      <a href="https://www.theurl.com">Visit https://www.theurl.com</a>
    </h5>
  </div>
</div>

请注意,我在第一个 div 中添加了“partner-website-element”的 ID(我只能向该元素添加一个类或一个 ID)。

到目前为止,这是我的 javascript:

<script>
    var cleanurl = document.getElementById("partner-website-element").getElementsByTagName('a').innerHTML;
    cleanurl.replace(/http(s):\/\/(www)/gi, '');
</script>

当我加载页面时,我在控制台中收到错误:

Uncaught TypeError: Cannot read property 'replace' of undefined

PS:我不确定我的正则表达式是否正确,因为到目前为止我只尝试替换http'',即cleanurl.replace(/http/gi, '');

标签: javascriptregexreplace

解决方案


这是它的香草JS:

console.log( `https://www.theurl.com`.replace(/https?:\/\/(www\.)?/gi, '') );
console.log( `http://www.theurl.com`.replace(/https?:\/\/(www\.)?/gi, '') );
console.log( `https://theurl.com`.replace(/https?:\/\/(www\.)?/gi, '') );

cleanurl失败了,因为您正在调用.innerHTML一个不提供该方法的对象。您需要循环cleanurl.innerHTML针对每个成员使用。


推荐阅读