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.

8
  • has it to be a regular expression? Commented Mar 22, 2018 at 17:48
  • /(.*).ts$/ this should check that the last 3 chars are '.ts' Commented Mar 22, 2018 at 17:49
  • Possible duplicate of Regex JavaScript image file extension Commented Mar 22, 2018 at 17:50
  • Possible duplicate of Javascript regex for matching/extracting file extension Commented Mar 22, 2018 at 17:50
  • @NinaScholz Yes, I need it to be a regular expression. Commented Mar 22, 2018 at 17:51

4 Answers 4

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'
Sign up to request clarification or add additional context in comments.

1 Comment

I need it not to match for "file.vue.ts". Your expression results in a match in this case.
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)));

Comments

1

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

^[a-zA-Z0-9\_\-]+(\.ts)$

Comments

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.

1 Comment

"file.ts" won't pass, because of "e" in "file", I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.