首页 > 解决方案 > 为什么我的 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 个字符。有谁知道我要去哪里错并且可以指出我正确的方向?

标签: javascriptjqueryhtml

解决方案


您需要将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;}


推荐阅读