0

I have the following string:

var fileName = $(this).val();

this will give me a result:

C:\fakepath\audio_recording_47.wav

what I want is to obtain : audio_recording_47.wav so, I need to trim it but I don't know how using javascript please help

souna
  • 43
  • 3
  • 3
    Have you tried to solve this yourself? Can you pleas share with us some of your attempts? – Lix Aug 13 '14 at 10:15
  • [`Get file name from full path`](http://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript) – Shubh Aug 13 '14 at 10:44

5 Answers5

3
filename.split('\\').reverse()[0];

This will split the path by slashes, to obtain each part. Then to keep it simple, i reverse the array, so the last part that you need is now the first; and get the first part.

Or, even more simply: filename.split('\\').pop(), which will get the last item from the array.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • 2
    Or you could use `pop()`, which would save you the cost of reversing the array. Or you could use `lastIndexOf()` and `substr()`, which would save you the cost of building an array in the first place. – Frédéric Hamidi Aug 13 '14 at 10:17
  • This won't split a UNIX-style path. You can also `split` with a regular expression, so it could be this: `filename.split(/[\\\/]/g).pop()`. – Toothbrush Aug 13 '14 at 13:23
  • @toothbrush For a UNIX path, just replace the \\ with a /. – Scimonster Aug 13 '14 at 14:56
1

You can do like this:

var fileName = $(this).val();
var path = fileName.split('\\');
var lastValue = path[path.length-1];
console.log(lastValue);//audio_recording_47.wav

Or, the shorter way you can do like this:

var fileName = $(this).val();
var path = fileName.split('\\').slice(-1);//audio_recording_47.wav
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

You could write a little function to return the base name of the path:

function basename(fn) {
    var x = fn.lastIndexOf("\\");

    if (x >= 0) return fn.substr(x + 1);
    return fn;
}

var filename = basename($(this).val());
M Oehm
  • 28,726
  • 3
  • 31
  • 42
0

This should do it:

var trimmedFileName = fileName.match(/[^\\]*$/);

It matches everything that isn't a \ until the end of the string.

Toothbrush
  • 2,080
  • 24
  • 33
icke
  • 1,568
  • 1
  • 19
  • 31
  • Your regular expression is incorrect. `$` marks the end of the string, but `^` marks the beginning of the string. – Toothbrush Aug 13 '14 at 10:37
0

You could use a regular expression, like this:

var fileName = this.value.replace(/(?:[^\\\/]*[\\\/])*/, '');

Also, there is no need to use that snippet of jQuery, as this.value is both faster and simpler.

Toothbrush
  • 2,080
  • 24
  • 33