2010-02-02 11 views
40

devo stringhe formattate come segue:
path/to/a/filename.txtJS: il modo più ottimizzato per rimuovere un nome file da un percorso in una stringa?

ora mi piacerebbe fare qualche manipolazione di stringhe che mi permette di rimuovere in modo molto efficiente la parte "nomefile.txt" da questo codice. In altre parole, voglio che la mia stringa diventi questa:
path/to/a/

Qual è il modo più efficiente per farlo? Attualmente sto dividendo la stringa e ricollegando gli elementi separati tranne che per l'ultimo, ma ho la sensazione che questo sia un modo davvero, DAVVERO inefficiente per farlo. Ecco il mio attuale, il codice inefficiente:

res.getPath = function(file) 
{ 
    var elem = file.split("/"); 
    var str = ""; 
    for (var i = 0; i < elem.length-1; i++) 
    str += elem[i] + "/"; 
    return str; 
} 
+0

Molto simile: http://stackoverflow.com/questions/2161511 – Gumbo

+0

'split' è in realtà molto veloce, ma sicuramente non è il modo * più veloce * ... – RedFilter

risposta

81

Usa lastIndexOf() per trovare la posizione dell'ultima barra e ottenere il parte prima della barra con sottostringa().

str.substring(0, str.lastIndexOf("/")); 
+0

Short, e funziona. Grazie! Non posso credere di non aver pensato di usare lastIndexOf()! – DaVince

+1

Si noti che questo restituirà una stringa con il nome file su URL come questo: 'http: //example.com/index.php? P = about/location' o' http: //ex.co/#/14185' – Kroltan

+1

Le barre in avanti nei parametri URL dovrebbero essere codificate per URL. –

10

ne dite di questo:

"path/to/a/filename.txt".split("/").slice(0, -1).join("/")+"/" 
1
function splitPath(path) { 
    var dirPart, filePart; 
    path.replace(/^(.*\/)?([^/]*)$/, function(_, dir, file) { 
    dirPart = dir; filePart = file; 
    }); 
    return { dirPart: dirPart, filePart: filePart }; 
} 

lì che va meglio

+0

Sto usando JS al di fuori di un browser, e sta dando me a "SyntaxError: classe di caratteri non terminata [" – DaVince

1

Se questo è quello di elaborare un nome di file da un modulo di upload di file, le specifiche HTML5 raccomanda il seguente codice:

function extractFilename(path) { 
    if (path.substr(0, 12) == "C:\\fakepath\\") 
    return path.substr(12); // modern browser 
    var x; 
    x = path.lastIndexOf('/'); 
    if (x >= 0) // Unix-based path 
    return path.substr(x+1); 
    x = path.lastIndexOf('\\'); 
    if (x >= 0) // Windows-based path 
    return path.substr(x+1); 
    return path; // just the filename 
} 

Riferimento: http://www.w3.org/TR/html5/number-state.html#file-upload-state http://www.w3.org/TR/html5/forms.html#file-upload-state-(type=file)

0
function getDirname(pathname, separator) { 
    var parts = pathname.split(separator); 
    if (parts[parts.length - 1].indexOf('.') > -1) { 
     return parts.slice(0, -1).join(separator) 
    } 
    return pathname; 
} 

Usage :

var dir = getDirname(url.parse(request.url).pathname, '/'); 

.

var dir = getDirname(path.join('foo', 'bar', 'text.txt'), path.sep); 
0

test/dir/lib/file- _09.ege.jpg - sarà quello di - test/dir/lib/

file- _09.ege.jpg - Sarà quello di - file- _09.ege.jpg

console.log("test - "+getPath('test/dir/lib/file- _09.ege.jpg')); 

    function getPath(path){ 
     path = path.match(/(^.*[\\\/]|^[^\\\/].*)/i); 
     if(path != null){ 
      return path[0]; 
     }else{ 
      return false; 
     }    
    } 

console.log("test - "+getPath('test/dir/lib/file- _09.ege.jpg')); 
 

 
     function getPath(path){ 
 
      path = path.match(/(^.*[\\\/]|^[^\\\/].*)/i); 
 
      if(path != null){ 
 
       return path[0]; 
 
      }else{ 
 
       return false; 
 
      }    
 
     }

Problemi correlati