2011-04-05 170 views

回答

0

你可以寫

var parts = filename.split('.'); 

parts[0]將包含"testfile",並parts[1]將是txt

如果字符串可能有多個. S,你可以寫

var filename = "test.file.txt"; 
var parts = /(.+)\.([^.]+)/.exec(filename); 

parts[1]將包含"text.file",並parts[2]txt

0

試試這個:

var fileName = "testfile.txt".replace(/\..*$/, ""); 
alert(fileName); 
+0

這裏不需要使用正則表達式。 – ThiefMaster 2011-04-05 15:19:53

+0

@ ThiefMaster:同意。剛剛發佈了一種可能的方式... – Chandu 2011-04-05 15:20:51

1
function splitFilename(filename) { 
    var dot = filename.lastIndexOf('.'); 
    if (dot === -1 || dot === 0) { // no extension 
     return [filename, '']; 
    } 
    return [filename.substr(0, dot), filename.substr(dot + 1)]; 
} 

例子:

js> splitFilename('a') 
a, 
js> splitFilename('.htaccess') 
.htaccess, 
js> splitFilename('test.blah.php') 
test.blah,php 
js> splitFilename('test.php') 
test,php 
js> splitFilename('test.') 
test,