javascript Reg Exp to match specific domain name

前端 未结 6 2122
小鲜肉
小鲜肉 2021-01-12 09:34

I have been trying to make a Reg Exp to match the URL with specific domain name.

So if i want to check if this url is from example.com what reg exp should be the bes

6条回答
  •  佛祖请我去吃肉
    2021-01-12 09:57

    Use indexOf javascript API. :)

    var url = 'http://api.example.com/api/url';
    
    var testUrl = 'example.com';
    
    if(url.indexOf(testUrl) !== -1) {
        console.log('URL passed the test');
    } else{
        console.log('URL failed the test');
    }
    

    EDIT:

    Why use indexOf instead of Regular Expression.

    You see, what you have here for matching is a simple string (example.com) not a pattern. If you have a fixed string, then no need to introduce semantic complexity by checking for patterns.

    Regular expressions are best suited for deciding if patterns are matched.

    For example, if your requirement was something like the domain name should start with ex end with le and between start and end, it should contain alphanumeric characters out of which 4 characters must be upper case. This is the usecase where regular expression would prove beneficial.

    You have simple problem so it's unnecessary to employ army of 1000 angels to convince someone who loves you. ;)

提交回复
热议问题