2013-02-10 31 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