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?

Cubi73
  • 1,891
  • 3
  • 31
  • 52

5 Answers5

13

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

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

alert(filename.substr(0, filename.lastIndexOf(".")));
Paddy
  • 33,309
  • 15
  • 79
  • 114
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.

KeyNone
  • 8,745
  • 4
  • 34
  • 51
  • This works, but when I use `foo.bar.something.else".match(/(.+)\..+$/mi);`, it should return the filename without extension – Cubi73 Feb 18 '14 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 '14 at 08:32
3

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

Uri Y
  • 840
  • 5
  • 13
  • 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 '14 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?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
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.

marionebl
  • 3,342
  • 20
  • 34