【发布时间】:2019-09-18 23:18:52
【问题描述】:
我正在尝试使用类似于
的东西/^(.*?)\.txt/
但我不想使用 .txt,而是想用变量替换它
【问题讨论】:
标签: javascript regex typescript
我正在尝试使用类似于
的东西/^(.*?)\.txt/
但我不想使用 .txt,而是想用变量替换它
【问题讨论】:
标签: javascript regex typescript
是的,您可以使用 RegExp 构造函数。
var extension = ".txt";
var reg = new RegExp("^(.*?)\\" + extension);
console.log(reg);
console.log(reg.test("test.txt"));
console.log(reg.test("test.pdf"));
【讨论】:
你可以使用:
function extMatch(ext){
return new RegExp('^(.*?)\\.'+ext+'$');
}
/* Even shorter, but messing with base prototypes is frowned upon.
Use at your leisure. */
String.prototype.extMatch=function(ext){
let match=this.match(extMatch(ext));
return match && match[1];
}
let str='foobar.css';
let ext='css';
console.log(str.match(extMatch(ext))[1]);
console.log(str.extMatch(ext));
console.log(str.extMatch('zip')); // null if no match
【讨论】: