确定string / url是否属于特定域

时间:2015-01-30 00:54:23

标签: javascript regex

我正在尝试使用RegExp中的JavaScript来确定当前字符串(代表网址)是否属于github.com域。

示例,如果http://developer.github.comhttp://subdomain.github.com返回true,否则返回false

尝试使用通配符代替子域,以允许http://.github.com之间任意数量的任何字符。/http://[a-z]*.github.com/ig

http://jsfiddle.net/bobbyrne01/nrp6pkkq/1/

js ..

var str0 = 'http://exämple.org/foo.html?baz=la#bumm';
var str1 = 'https://developer.github.com/v3/';
var str2 = 'http://developer.github.com/v3/';
var str3 = 'http://test.github.com/v3/';
var str4 = 'http://example.org';

var patt = new RegExp("/http://[a-z]*.github.com/ig");
document.getElementById('results').innerHTML = patt.test(str0) + '<br/>';
document.getElementById('results').innerHTML += patt.test(str1) + '<br/>';
document.getElementById('results').innerHTML += patt.test(str2) + '<br/>';
document.getElementById('results').innerHTML += patt.test(str3) + '<br/>';
document.getElementById('results').innerHTML += patt.test(str4) + '<br/>';

html ..

<div id="results"></div>

output ..

false
false
false
false
false

预期产出:

false
false
true
true
false

3 个答案:

答案 0 :(得分:1)

如果你使用带有双引号的RegExp构造函数作为分隔符,那么你不需要另一个分隔符,即/

var patt = new RegExp("http://[a-z]*\\.github\\.com", "ig");

示例:

> var patt = new RegExp("http://[a-z]*\\.github\\.com", "ig");
> var str0 = 'http://exämple.org/foo.html?baz=la#bumm';
undefined
> patt.test(str0)
false
> var str1 = 'https://developer.github.com/v3/';
> patt.test(str1)
false
> var str2 = 'http://developer.github.com/v3/';
> patt.test(str2)
true

答案 1 :(得分:1)

我真的建议您使用Dom解析器而不是Regex来解析URL。使用此解决方案:https://stackoverflow.com/a/13465791/970247。您将能够像这样检索域名:

var myURL = parseURL('https://developer.github.com/v3/');
myURL.host;     // = 'developer.github.com'

答案 2 :(得分:1)

您可以将此模式与RegExp.prototype.test()方法一起使用:

function isDomain(domain, url) {
    var pat = '^https?://(?:[^/@:]*:[^/@]*@)?(?:[^/:]+\.)?' + domain + '(?=[/:]|$)';
    var re = new RegExp(pat, 'i');
    return re.test(url);
}

var url = 'http://test.github.com/v3/';

console.log(isDomain('github.com', url));

或者您可以将其实现为String方法:

String.prototype.isDomain = function (domain) {
    var pat = '^https?://(?:[^/@:]*:[^/@]*@)?(?:[^/:]+\.)?' + domain + '(?=[/:]|$)';
    var re = new RegExp(pat, 'i');
    return re.test(this);
}

console.log(url.isDomain('github.com'));

模式细节:

^ # anchor for the start of the string

https?://  # scheme (note that you can improve it addying ftp, sftp...)

(?:[^/@:]*:[^/@]*@)?  # optional login/password

(?:[^/:]+\.)?         # optional subdomain

github\.com           # the domain

(?=[/:]|$)            # check if the domain is followed by:
                      #   - a path /
                      #   - a port :80
                      #   - the end of the string $
                      # to prevent false positives