Regex that matches anything not ending in .json

前端 未结 4 1025
天命终不由人
天命终不由人 2020-12-21 01:03

For a web app I\'m trying to come up with a javascript regex that matches anything not ending in .json. Sounds simple but I\'m finding it pretty damn hard.

相关标签:
4条回答
  • 2020-12-21 01:23

    Try /^(?!.*\.json$).*$/

    /^(?!.*\.json$).*$/.test("foo.json")
    false
    /^(?!.*\.json$).*$/.test("foo")
    true
    /^(?!.*\.json$).*$/.test("foo.html")
    true
    
    0 讨论(0)
  • 2020-12-21 01:28

    maybe instead of testing "match (not .json)" you could test "not match (.json)", which is easy ?

    0 讨论(0)
  • 2020-12-21 01:46

    You can always just get the file extension and then compare it.

    Regex to find file extension

    /\.[^.]*$/

    get the file extension with

    var extension = /\.[^.]*$/.exec("something.json");
    
    if(extension[0] === ".json"){
        //do something
    }
    
    0 讨论(0)
  • 2020-12-21 01:47

    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.

    0 讨论(0)
提交回复
热议问题