4

I have a list of filenames like

index.min.html
index.dev.html
index.min.js
index.dev.js
There.are.also.files.with.multiple.dots.and.other.extension

I want to cut off the extensions of the filenames, but the problem is that I can only use match for this task.

I tried many regular expressions looking like "index.min.html".match( /^((?!:(\.[^\.]+$)).+)/gi ); to select the filename without the last dot and extension, but they selected either the hole filename, nothing or the part before the first dot. Is there a way to select only the filename without extension?

1
  • 1
    Can you explain on why you have to use match?
    – marionebl
    Feb 18, 2014 at 14:16

5 Answers 5

13

Why regex? Simple substring expressions make this a lot simpler:

var filename = 'index.something.js.html';

alert(filename.substr(0, filename.lastIndexOf(".")));
3

I'd go for

/(.+)\..+$/mi

demo @ regex101

See the demo, especially the matches. It only gives you the filename without the last . and the characters afterwards.

2
  • This works, but when I use foo.bar.something.else".match(/(.+)\..+$/mi);, it should return the filename without extension
    – Cubi73
    Feb 18, 2014 at 16:36
  • @Cubinator73 this isn't possible with regexes. the match-method will always return the... well... match. For your scenario you'll always have to match the full name and capture the interesting part. Thus the filename without extension is simply contained in a capturing group that you can access on the match. When you run the match you posted in a browserconsole you will see that match[1] is the part that you want to get (foo.bar.something). match[0] is always the whole match and every index > 0 are the capturing groups.
    – KeyNone
    Feb 19, 2014 at 8:32
3

How about this one: (.*)\.[^\.]+ See http://regex101.com/r/xI6qM0

1
  • This works too, but, as I said to Basti M, when I use foo.bar.something.else".match(/(.*)\.[^\.]+/gi);, it should return the filename without extension
    – Cubi73
    Feb 18, 2014 at 16:37
1

A simpler solution would be to just slice off the last element:

var a = "index.min.html";
var b = a.split('.').slice(0, -1).join('.');

Or, even better, using JavaScript's String function substr:

var b = a.substr(0, a.lastIndexOf("."));

Why do you have to use match?

1
  • 1
    This works also great. Paddy's is shorter, but thank you too. :)
    – Cubi73
    Feb 18, 2014 at 16:38
0

Could do the trick, too:

function baseName(str) {
    if (typeof str !== 'string') return;
    var frags = str.split('.')
    return frags.splice(0,frags.length-1).join('.');    
}

Repl:http://repl.it/OvI

jsPerf: http://jsperf.com/string-extension-splits

Result:

substr is the fastest of all options in this thread. Kudos to the other guys.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.