For a web app I'm trying to e up with a javascript regex that matches anything not ending in .json
. Sounds simple but I'm finding it pretty damn hard.
I first wanted to do it like this: ^.*(?!\.json$)
, but that obviously didn't work as it simply matches the entire string. Then I tried ^[^\.]*(?!\.json$)
but that matches ab
in abc.json
.
I've e so far as to e up with two regexes that do the job, but I want to have one regex that can do this.
// Match anything that has a dot but does not end in .json
^.*\.(?!json$)
// Match anything that doesn't have a dot
^[^\.]*$
I like to test them.
I am using the regexp as part of ExpressJS route definition in app.get(REGEXP, routes.index)
.
For a web app I'm trying to e up with a javascript regex that matches anything not ending in .json
. Sounds simple but I'm finding it pretty damn hard.
I first wanted to do it like this: ^.*(?!\.json$)
, but that obviously didn't work as it simply matches the entire string. Then I tried ^[^\.]*(?!\.json$)
but that matches ab
in abc.json
.
I've e so far as to e up with two regexes that do the job, but I want to have one regex that can do this.
// Match anything that has a dot but does not end in .json
^.*\.(?!json$)
// Match anything that doesn't have a dot
^[^\.]*$
I like http://regex101./#javascript to test them.
I am using the regexp as part of ExpressJS route definition in app.get(REGEXP, routes.index)
.
4 Answers
Reset to default 12Try /^(?!.*\.json$).*$/
/^(?!.*\.json$).*$/.test("foo.json")
false
/^(?!.*\.json$).*$/.test("foo")
true
/^(?!.*\.json$).*$/.test("foo.html")
true
You can always just get the file extension and then pare it.
Regex to find file extension
/\.[^.]*$/
get the file extension with
var extension = /\.[^.]*$/.exec("something.json");
if(extension[0] === ".json"){
//do something
}
maybe instead of testing "match (not .json)" you could test "not match (.json)", which is easy ?
I would create a regex to match .json and then when you check for it reverse the logic with a
match == false
That would be much simpler and it shows what you are trying to do making it a lot more obvious to other programmers.