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/
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)"
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.