简体   繁体   English

如何将string.replace与正则表达式一起使用

[英]How do I use string.replace with regular expressions

I'm trying to strip the file extension from a file name using a regular expression and String.replace 我正在尝试使用正则表达式和String.replace从文件名中删除文件扩展名

I'm using this regex: /^.*(\\..*)/ which should capture the extension, or at least everything after a . 我正在使用这个正则表达式: /^.*(\\..*)/应该捕获扩展名,或者至少是一切后的所有内容.

Doing str.replace(/^.*(\\..*)/,""); str.replace(/^.*(\\..*)/,""); just gives me a blank string. 只给我一个空白的字符串。

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

fiddle: http://jsfiddle.net/KAK82/ 小提琴: 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)"

Fiddle 小提琴

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"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM