0

I'm trying to strip the file extension from a file name using a regular expression and String.replace

I'm using this regex: /^.*(\..*)/ which should capture the extension, or at least everything after a .

Doing str.replace(/^.*(\..*)/,""); just gives me a blank string.

Doing str.replace(/^.*(\..*)/,""); gives me ".pdf"

fiddle: http://jsfiddle.net/KAK82/

  • How many dots are there in your filenames? You could split them by dot and take the first part? – putvande Jan 31 '14 at 00:03
  • possible duplicate of [Regular expression to remove a file's extension](http://stackoverflow.com/questions/1818310/regular-expression-to-remove-a-files-extension) – Ryan Jan 31 '14 at 00:05
  • @Ryan Answers to that question do not use String.replace. I want to know how to use `string.replace` with regular expressions. Stripping the file name is a problem that can be solved many different ways. –  Jan 31 '14 at 00:07
  • @putvande I could, but then I wouldn't be using `string.replace` with regular expressions. –  Jan 31 '14 at 00:08
  • Try using http://regex101.com – Joeytje50 Jan 31 '14 at 00:10
  • @Joeytje50 this appears to be just a regex tester. According to another regex tester that I use, it works in that it captures what I intend for it to capture on the types of strings I intend to use it on. I don't think this tool will help me –  Jan 31 '14 at 00:12

2 Answers2

1

You need to capture (with (.*)) the first bit of you file, not the extension itself:

var string = "CommercialTribe - Copy (14).pdf"
var re = /^(.*)\..*/;
console.log(string.replace(re,'$1'));

// Output: "CommercialTribe - Copy (14)"

Fiddle

putvande
  • 15,068
  • 3
  • 34
  • 50
1

There are two options here:

  • Only match the extension and replace it with an empty string:

    str.replace(/\.[^.]*$/, "");
    
  • Match the entire string and capture everything but the extension, and then replace with the contents of that match:

    str.replace(/^(.*)\..*$/, "$1");
    
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306