Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

javascript - Regular expression to remove a file's extension

I am in need of a regular expression that can remove the extension of a filename, returning only the name of the file.

Here are some examples of inputs and outputs:

myfile.png     -> myfile
myfile.png.jpg -> myfile.png

I can obviously do this manually (ie removing everything from the last dot) but I'm sure that there is a regular expression that can do this by itself.

Just for the record, I am doing this in JavaScript

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just for completeness: How could this be achieved without Regular Expressions?

var input = 'myfile.png';
var output = input.substr(0, input.lastIndexOf('.')) || input;

The || input takes care of the case, where lastIndexOf() provides a -1. You see, it's still a one-liner.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...