开发者

How to write a Reg to match with the URLs in Javascript?

I have a list of urls like this:

http://www.mylocal.com
http://v1.mylocal.com
http://v2.mylocal.com
http://www.mylocal2.com
http://www.mylocal3.com

And I want to write a JS that if I define the search string be "*.mylocal.com" , then it will return www.myloc开发者_StackOverflow中文版al.com v1.mylocal.com and v2.myloca.com. And if the search string is "www.local.com", then it will return only www.mylocal.com

how should I write it?


The following regex will match what you want when given a host string:

var reg = new RegExp('^https?://([^.]*' + host + ')');

So, for example:

var host = '.mylocal.com';
reg.exec('http://www.mylocal.com');  // ["http://www.mylocal.com", "www.mylocal.com"]
reg.exec('http://v1.mylocal.com/path');   // ["http://v1.mylocal.com", "v1.mylocal.com"]
reg.exec('https://v3.mylocal.com'); // ["https://v3.mylocal.com", "v3.mylocal.com"]

host = 'www.mylocal.com';
reg.exec('http://www.mylocal.com');  // ["http://www.mylocal.com", "www.mylocal.com"]
reg.exec('http://v1.mylocal.com/path');   // null
reg.exec('https://v3.mylocal.com'); // null

You could also refer to the following post for a full URI regex: Regular expression validation for URL in ASP.net.


If you want to search on each part of the URL then do just that. split the URL into 3 searching strings, then run a match of each against your split search terms, this way you can control matching at the beginning and end of each term, and if you would like can order the rest of the terms appropriately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜