2011-05-15 256 views
1

我正在嘗試爲我創建的網站創建導航系統。我花了幾個小時試圖弄清楚,但我不明白爲什麼它不工作 我試圖用變量文件名替換所有「index.html」的事件。Javascript String.Replace does not work?

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.htm」明明不是「的index.html」,它消​​除了「/」從輸出,所以我得到「 HTTP://localhost/xxxindex.html/newpage.html」。

+0

爲什麼不簡單'url.replace(「/ index.html」,文件名)'? – 2011-05-15 12:25:16

+2

該代碼實際上工作得很好。 – Pointy 2011-05-15 12:26:51

+0

如果我是你,我會提出一個'alert(文件名)'來確保你知道正在發生的一切。 – Pointy 2011-05-15 13:11:22

回答

0

你正在指定一個字符串作爲正則表達式。嘗試指定的子串作爲第一PARAM替換(),像這樣:

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

See docs for String.replace

+0

代碼已經按照書面形式工作。 – Pointy 2011-05-15 12:28:31

0

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

小數點任何單個 字符匹配除了新行 字符。因此,例如, 字符串「The cat eats moths」 正則表達式/.t/gi將匹配 'cat'中的字母at, 'eats'和'ot'中的字母'at'。 '飛蛾',但不是 'The'的最初'T'。

所以,你必須逃脫週期:

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

但是「。」事實上會匹配「。」在「index.html」就好了。 – Pointy 2011-05-15 12:28:22

+0

@有點,是的......如果你逃脫它。 – Kon 2011-05-15 12:30:21

+0

它也會匹配「。」如果你**不要逃避它,因爲「。」匹配任何字符 - 包括「。」。 – Pointy 2011-05-15 13:10:16

1

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

它是這樣的:
str.replace("s1", "s2")不對str做任何事情。

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

通知的LHS明確地捕捉替代的結果。

希望它有幫助:)