2010-11-12 77 views
3

下更換的JavaScript與string.replace()

"index.html".replace('\.html$', '_fr.html'); 

回報 「的index.html」,表示第一個參數不匹配任何東西。但是,如果我去掉「$」

"index.html".replace('\.html', '_fr.html'); 

則第一個參數比賽和「index_fr.html」返回。

回到第一個例子,有人可以解釋爲什麼「.html $」似乎不匹配「index.html」?

回答

5

因爲這不是一個正則表達式 - 在JavaScript中的正則表達式的文字是這樣的:

/\.html$/ 

不帶引號。 String.replace接受一個字符串或一個正則表達式。