javascript - 为什么我的 URL 字符串没有按预期缩短?
问题描述
我有一个名为siteURL的变量,它是使用window.location.href设置的。
我想剪掉最后 10 个字符,在这种情况下是 ...index.html。
var siteURL = window.location.href;
if (siteURL.endsWith('index.html')) {
siteURL.substring(0, siteURL.length - 10);
}
//log the output
console.log(siteURL);
我正在尝试这个,但它似乎并没有删除最后 10 个字符。有谁知道我要去哪里错并且可以指出我正确的方向?
解决方案
您需要将String.substring()的返回值存储回siteUrl
变量中。还要注意那些strings
是不可变的Javascript
(也检查下一个参考:JavaScript 字符串是不可变的吗?我需要 JavaScript 中的“字符串生成器”吗?)。
var siteURL = "some/url/with/index.html";
if (siteURL.endsWith('index.html'))
{
siteURL = siteURL.substring(0, siteURL.length - 10);
}
console.log(siteURL);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
但是,对于您想要的更好的方法是将String.replace()与正则表达式一起使用:
var siteURL = "some/url/with-index.html/index.html";
siteURL = siteURL.replace(/index\.html$/, "");
console.log(siteURL);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
推荐阅读
- docker - Docker Desktop kubernates 上用于 Ingress 的空地址
- c# - 在 C# 中按搜索文本相关性排序列表
- python-3.x - 如何在 Juypter 笔记本中使用/安装 python 代码/文件
- php - PHP正则表达式,删除特定属性
- text - 在 SwiftUI 中,Picker 扩展为占据 HStack 内的整个空间
- tabulator - 制表符:使用键盘访问列
- javascript - 您知道连接多方、强大和文件上传之间的区别吗?它们是如何工作的?
- php - USB网络服务器的自动运行
- java - 如何在另一种方法中使用布尔值?
- google-bigquery - 如何根据数组中的值删除 BigQuery 中的记录?