2013-02-10 32 views

回答

7

試試這個:

var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; 
url.replace(/\.[^.]*$/g, ''); // would replace all file extensions at the end. 

// or in case you only want to remove .html, do this: 
var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; 
url.replace(/\.html$/g, ''); 

包括在正則表達式時,$字符相匹配的文本字符串的結尾。在變體a中,您可以從「。」開始。並從該字符中刪除所有內容,直到字符串結束。在變體2中,您將其縮減爲確切的字符串「.html」。這更多關於正則表達式而不是關於JavaScript。要了解更多信息,請點擊這裏tutorials

3

你只需要使用replace()

var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; 
var one = url.replace('.html', ''); 

如果要確保您只刪除從字符串使用正則表達式的末尾.html

var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; 
var one = url.replace(/\.html$/', ''); 

$表示只有字符串的最後一個字符應該是che cked。

+0

當輸入中的某個其他上下文中出現字符串「.html」時,這將不起作用。 – Philipp 2013-02-10 12:17:39

+0

這是真的,但爲什麼它,除非你有一個可怕的URL結構。 – 2013-02-10 12:24:59

+0

你的意思是除非*某人在整個互聯網*上有一個可怕的URL結構。另外,關於以html開頭的域名呢? – Philipp 2013-02-10 12:30:32

3
var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; 
var trimmedUrl = url.replace('.html', ''); 
2

你可以串起來slice最後點:

var url = 'http://this.is.my.url:7/directory1/directory2/index.html'; 
url = url.slice(0,url.lastIndexOf('.')); 
    //=> "http://this.is.my.url:7/directory1/directory2/index" 

或者在同一行:

var url = ''.slice.call(
      url='http://this.is.my.url:7/directory1/directory2/index.html', 
      0,url.lastIndexOf('.') ); 
2

使用正則表達式,它從捕獲與自身取代一切(.*)組(不包括尾隨.html)。

var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; 
var one = url.replace(/(.*)\.html/, '$1'); 
        ^^   ^^ 
// Capture group ______| |__________|| 
//     Capture ----> Get captured content