[英]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/
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.