2

Is there a way how to write a JavaScript regular expression that would recognize .ts file extension for this:

"file.ts" 

but would fail on this:

"file.vue.ts"

What I need is, if the file name ends with .vue.ts, it shouldn't be handled as a .ts file.

I've tried a lot of things with no success.

Update: It needs to be a regular expression, because that's what I'm passing to a parameter of a function.

Tom Shane
  • 694
  • 7
  • 18

4 Answers4

3

You could look for a previous coming dot and if not return true.

console.log(["file.ts", "file.vue.ts"].map(s => /^[^.]+\.ts$/.test(s)));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

Regex for that is ^[^.]+.ts$

var x=/^[^.]+.ts$/;
console.log(x.test("file.ts"));
console.log(x.test("file.vue.ts"));
console.log(x.test("file.vue.ts1"));

Explanation:-

^[^.]+.ts$

^        ---> start of line
[^.]+    ---> match anything which is not '.' (match atleast one character)
^[^.]+   ---> match character until first '.' encounter
.ts      ---> match '.ts'
$        ---> end of line
.ts$     ---> string end with '.ts'
yajiv
  • 2,901
  • 2
  • 15
  • 25
1

This will work except for special characters. Will allow for uppercase letters, lowercase letters, numbers, underscores, and dashes:

^[a-zA-Z0-9\_\-]+(\.ts)$
1
const regex = /(.*[^.vue]).ts/g;
abc.ts.ts Matches
abc.xyx.htm.ts Matches
abc.vue.ts Fails
xyz.abx.sxc.vue.ts Fails

Javascript regex should be this one.

Nadeem Ahmad
  • 140
  • 1
  • 6