Using javascript, how can I capture the string example.com
from the current domain http://exam开发者_运维百科ple.com/bar?param=value
or https://www.example.com
?
My first attempt doesn't work correctly:
https?://w?w?w?[.]?[^?/]
You don't need regex for this! Let the browser parse it for you:
var a = document.createElement('a');
a.href = 'http://foo.com/bar?param=value';
a.hostname; // "foo.com"
Voila!
If doing this in JavaScript, you don't even need a regex. You can use the location object like so:
var host = window.location.host;
This link has more information about how to get other parts of the URL: http://www.comptechdoc.org/independent/web/cgi/javamanual/javalocation.html.
For full cross-browser compatibility simply go with the document object, not window:
var theHost = document.location.host;
If you're really sold on using regular expressions rather than built-in tools in the language (e.g. PHP's parse_url
function) then something like:
(?:(\w+)://)([^/]+)(/\w+)?
will do it in a very rough way, with the hostname in subgroup 2. This is just a quick-and-dirty hack though (and won't work in all cases), and I would advise using the language's built-in tools.
If it's Javascript and the current URL, look at window.location.host
or window.location.hostname
.
精彩评论