javascript - 如何从页面上的 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, '');
解决方案
这是它的香草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
针对每个成员使用。
推荐阅读
- metrics - 如何同时添加 sum() 和 avg()?
- javascript - 使用保存按钮在新工作表中自动复制数据
- javascript - 使用 webcomponent 中的 prismjs 显示带有语法突出显示的代码片段
- javascript - HTML、Javascript:读出单元格输入,设置为选择
- python - 是否可以使用 python 截取网站的屏幕截图而不必在我的电脑上实际打开网站?
- wordpress - 如何在 WooCommerce 的自定义下拉列表中添加“按产品标签按字母顺序排序”?
- r - R中带有“ldpy”的多重线性回归问题
- angular - 我们如何在 Angular 前端进行密码确认?
- mongodb - 如何为 MongoDB 设置 Ec2,以便 RAM 和存储根据他们的需求自动增加?
- javascript - 如何使用javascript增量方法增加数据库中的计数?