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

2
  • 3
    Have you tried to solve this yourself? Can you pleas share with us some of your attempts? Commented Aug 13, 2014 at 10:15
  • Get file name from full path Commented Aug 13, 2014 at 10:44

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 For a UNIX path, just replace the \\ with a /.
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());

Comments

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

Comments

0

This should do it:

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

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

1 Comment

Your regular expression is incorrect. $ marks the end of the string, but ^ marks the beginning of the string.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.