0

I wanna check the file is css file or not using regular expression. I tried

new RegExp(".css$").test("a.css"); //true 

but it is matching filename.acss which is correct. I want regex to match a valid .css file only. I need following cases .

new RegExp(".css$").test("a.acss"); //false
new RegExp(".css$").test(".css"); //false
new RegExp(".css$").test("a.cssa"); //false
new RegExp(".css$").test("a.css"); //true 
3
  • 1
    "match a valid .css file" do you mena that the file extention as a string is .css or the file is the right mime type? Commented Jul 17, 2015 at 10:32
  • 1
    regular expressions are overkill for this simple task. simply test if the ending of the string is ".css" and if the length of the file name is >= 4. more efficient! Commented Jul 17, 2015 at 10:53
  • 1
    I suggest re-reading some basic regexp tutorials. You'll quickly encounter the . character which matches anything, and needs to be escaped if you mean a real period. Commented Jul 17, 2015 at 10:57

1 Answer 1

2

.: (The decimal point) matches any single character except the newline character.

You need to escape . by preceding \ to match . literal.

var regex = /.\.css$/; // /\S+\.css$/; // /[\w\d]+\.css$/
regex.test("a.css");

Exaples

var regex = /.\.css$/;

alert(regex.test("a.acss")); // false
alert(regex.test(".css")); // false
alert(regex.test("a.cssa")); // false
alert(regex.test("a.css")); // true

Sign up to request clarification or add additional context in comments.

9 Comments

it is matching to regex.test(".css"); also . which I don't want
bro I want to avoid .css also . 2nd test must give false
Just use .+\.css$ then. That requires at least one more character in front of the extension.
\S+\.css$ will not work for file systems that allow white spaces in file names. To have a working regex that works with any characters allowed by a file system and any character set, use .+\.css$.
Downvoter, Can something be improved? Please add comment here
|

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.