簡體   English   中英

JavaScript String.Replace不起作用?

[英]Javascript String.Replace doesnt work?

我目前正在嘗試為正在創建的網站創建導航系統。 我花了數小時試圖弄清楚這一點,但是我不明白為什么它不起作用,我試圖用變量文件名替換所有出現的“ index.html”。

function changeSideNav(filenames)
{   
    var urlarray = window.location.href.split("?");
    var url = urlarray[0];
    alert(url); // This returns "http://localhost/xxx/index.html"
    var urlspl = url.replace(/index.html/gi,filenames);
    alert(url.replace(/index.html/i,filenames) +'/'+ filenames); //This returns "http://localhost/xxx/index.html/newpage.html" (if pram was newpage.html).
    //i txpected it to return "http://localhost/xxx//newpage.html"
    //set a new source
    document.getElementById('SideNavIframe').src = urlspl +'/'+ filenames;
}

編輯:我發現這很奇怪:如果我嘗試替換“ /index.html”而不是“ index.html”,它將從輸出中刪除“ /”,因此我得到“ http://localhost/xxxindex.html” /newpage.html”。

不知道這是否是您的概率。 但是我在這個問題上停留了一個小時。

這里是:
str.replace("s1", "s2")對str無效。

您需要做:
str=str.replace("s1", "s2");

請注意,LHS明確記錄了替換結果。

希望能幫助到你 :)

您正在將字符串指定為正則表達式。 嘗試將子字符串指定為replace()的第一個參數,如下所示:

var url = "http://localhost/xxx/index.html";
url.replace('index.html','changed.html');  // add 'gi' as 3rd param for all occurrences

請參閱文檔以獲取String.replace

來自http://www.devguru.com/technologies/ecmascript/quickref/regexp_special_characters.html

小數點與換行符以外的任何單個字符匹配。 因此,例如,使用字符串“貓吃蛾子”,正則表達式/.t/gi將匹配“ cat”中的字母“ at”,“ eats”中的“ at”和“ moths”中的“ ot”,但不是“ The”的首字母“ T”。

因此,您必須避開句號:

url.replace(/index\.html/gi,filenames)

暫無
暫無

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

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