簡體   English   中英

為什么我的URL字符串沒有縮短?

[英]Why isn't my URL string being shortened as expected?

我有一個名為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變量中。 還需要注意的是stringsinmutablesJavascript (查看下一個引用過: ?是的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;} 

您正在執行操作,只需要實際分配值即可。

siteURL = siteURL.substring(0, siteURL.length - 10);

你可以做:

var newStr = siteURL.substring(0, siteURL.length-10);

var newStr = siteURL.substr(0, siteURL.length-10);

var newStr = siteURL.slice(0, siteURL.length-10);

他們中的任何一個都可以工作:

console.log(newStr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM