Я просто разместил своего рода RFC, который может вам помочь: Разделить вектор на куски в R
x = data.frame(num = 1:26, let = letters, LET = LETTERS)
## number of chunks
n <- 2
dfchunk <- split(x, factor(sort(rank(row.names(x))%%n)))
dfchunk
$`0`
num let LET
1 1 a A
2 2 b B
3 3 c C
4 4 d D
5 5 e E
6 6 f F
7 7 g G
8 8 h H
9 9 i I
10 10 j J
11 11 k K
12 12 l L
13 13 m M
$`1`
num let LET
14 14 n N
15 15 o O
16 16 p P
17 17 q Q
18 18 r R
19 19 s S
20 20 t T
21 21 u U
22 22 v V
23 23 w W
24 24 x X
25 25 y Y
26 26 z Z
Cheers, Sebastian
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"
Сегодня я встречаю эту проблему, и я нашел: URL - веб-API MDN
var url = new URL("http://test.example.com/dir/subdir/file.html#hash");
Это возвращение:
{ hash:"#hash", host:"test.example.com", hostname:"test.example.com", href:"http://test.example.com/dir/subdir/file.html#hash", origin:"http://test.example.com", password:"", pathname:"/dir/subdir/file.html", port:"", protocol:"http:", search: "", username: "" }
Надеюсь, что я первый вклад поможет вам!
Разбор URL-адресов в нескольких браузерах работает вокруг проблемы относительного пути для IE 6, 7, 8 и 9:
function ParsedUrl(url) {
var parser = document.createElement("a");
parser.href = url;
// IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
// is just a pathname, that is, "/example" and not "http://domain.com/example".
parser.href = parser.href;
// IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
// so we take the protocol/host from window.location and place them manually
if (parser.host === "") {
var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
if (url.charAt(1) === "/") {
parser.href = newProtocolAndHost + url;
} else {
// the regex gets everything up to the last "/"
// /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
// "/" is inserted before because IE takes it of from pathname
var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
parser.href = newProtocolAndHost + currentFolder + url;
}
}
// copies all the properties to this object
var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
for (var i = 0, n = properties.length; i < n; i++) {
this[properties[i]] = parser[properties[i]];
}
// pathname is special because IE takes the "/" of the starting of pathname
this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
}
Использование ( demo JSFiddle здесь ):
var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment");
Результат:
{
hash: "#fragment"
host: "www.example.com:8080"
hostname: "www.example.com"
href: "http://www.example.com:8080/path?query=123#fragment"
pathname: "/path"
port: "8080"
protocol: "http:"
search: "?query=123"
}
, найденный здесь: https://gist.github.com/jlong/2428561
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"
parser.origin; // => "http://example.com:3000"
parser = location;
, и все следующие строки будут работать. Пробовал это в Chrome и IE9 только сейчас.
– Lee Meador
26 April 2013 в 18:20
pathname
не включает главную косую черту в IE. Идите фигуру. : D
– nevelis
21 February 2014 в 08:45
Ответ freddiefujiwara довольно хорош, но мне также необходимо поддерживать относительные URL-адреса в Internet Explorer. Я придумал следующее решение:
function getLocation(href) {
var location = document.createElement("a");
location.href = href;
// IE doesn't populate all link properties when setting .href with a relative URL,
// however .href will return an absolute URL which then can be used on itself
// to populate these additional fields.
if (location.host == "") {
location.href = location.href;
}
return location;
};
Теперь используйте его для получения необходимых свойств:
var a = getLocation('http://example.com/aa/bb/');
document.write(a.hostname);
document.write(a.pathname);
Пример JSFiddle: http://jsfiddle.net / 6AEAB /
var locationHost = (location.port !== '80' && location.port !== '443') ? location.host : location.hostname;
var locationOrigin = location.protocol + '//' + locationHost;
– rhoster
7 April 2016 в 22:58
var loc = window.location; // => "http://example.com:3000/pathname/?search=test#hash"
возвращает currentUrl.
Если вы хотите передать свою собственную строку в качестве URL-адреса ( не работает в IE11 ):
var loc = new URL("http://example.com:3000/pathname/?search=test#hash")
Затем вы можете разобрать его так:
loc.protocol; // => "http:"
loc.host; // => "example.com:3000"
loc.hostname; // => "example.com"
loc.port; // => "3000"
loc.pathname; // => "/pathname/"
loc.hash; // => "#hash"
loc.search; // => "?search=test"
Вы также можете использовать функцию parse_url()
из проекта php.js .
Код:
parse_url('http://username:password@hostname/path?arg=value#anchor');
Результат:
{
scheme: 'http',
host: 'hostname',
user: 'username',
pass: 'password',
path: '/path',
query: 'arg=value',
fragment: 'anchor'
}
Прекратите изобретать колесо. Используйте https://github.com/medialize/URI.js/
var uri = new URI("http://example.org:80/foo/hello.html");
// get host
uri.host(); // returns string "example.org:80"
// set host
uri.host("example.org:80");
Способ AngularJS - скрипка здесь: http://jsfiddle.net/PT5BG/4/
<!DOCTYPE html>
<html>
<head>
<title>Parse URL using AngularJS</title>
</head>
<body ng-app ng-controller="AppCtrl" ng-init="init()">
<h3>Parse URL using AngularJS</h3>
url: <input type="text" ng-model="url" value="" style="width:780px;">
<ul>
<li>href = {{parser.href}}</li>
<li>protocol = {{parser.protocol}}</li>
<li>host = {{parser.host}}</li>
<li>hostname = {{parser.hostname}}</li>
<li>port = {{parser.port}}</li>
<li>pathname = {{parser.pathname}}</li>
<li>hash = {{parser.hash}}</li>
<li>search = {{parser.search}}</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script>
function AppCtrl($scope) {
$scope.$watch('url', function() {
$scope.parser.href = $scope.url;
});
$scope.init = function() {
$scope.parser = document.createElement('a');
$scope.url = window.location;
}
}
</script>
</body>
</html>
$document
и $window
– Cherniv
28 September 2014 в 07:26
Для тех, кто ищет современное решение, которое работает в IE, Firefox и Chrome:
Ни одно из этих решений, использующих элемент гиперссылки, не будет работать так же, как в хром. Если вы передадите недопустимый (или пустой) url на chrome, он всегда будет возвращать хост, из которого вызывается сценарий. Таким образом, в IE вы получите пустое, тогда как в Chrome вы получите localhost (или что-то еще).
Если вы пытаетесь посмотреть реферер, это обманчиво. Вы хотите убедиться, что хост, которого вы получили, был в исходном URL-адресе, чтобы иметь дело с этим:
function getHostNameFromUrl(url) {
// <summary>Parses the domain/host from a given url.</summary>
var a = document.createElement("a");
a.href = url;
// Handle chrome which will default to domain where script is called from if invalid
return url.indexOf(a.hostname) != -1 ? a.hostname : '';
}
Вот простая функция, использующая регулярное выражение, которое имитирует поведение тегов a
.
Плюсы
Минусы
-
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
href: href,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
-
getLocation("http://example.com/");
/*
{
"protocol": "http:",
"host": "example.com",
"hostname": "example.com",
"port": undefined,
"pathname": "/"
"search": "",
"hash": "",
}
*/
getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
"protocol": "http:",
"host": "example.com:3000",
"hostname": "example.com",
"port": "3000",
"pathname": "/pathname/",
"search": "?search=test",
"hash": "#hash"
}
*/
EDIT:
Вот разбивка регулярного выражения
var reURLInformation = new RegExp([
'^(https?:)//', // protocol
'(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
'(/{0,1}[^?#]*)', // pathname
'(\\?[^#]*|)', // search
'(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
http://192.168.1.2
? (или просто URL-адрес без конечного /
)
– Karl Stephen
3 May 2016 в 21:33
Простое и надежное решение с использованием шаблона модуля. Это включает в себя исправление для IE, где pathname
не всегда имеет ведущую прямую слэш (/
).
Я создал Gist вместе с JSFiddle , который предлагает более динамический парсер.
var URLParser = (function (document) {
var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
var self = function (url) {
this.aEl = document.createElement('a');
this.parse(url);
};
self.prototype.parse = function (url) {
this.aEl.href = url;
if (this.aEl.host == "") {
this.aEl.href = this.aEl.href;
}
PROPS.forEach(function (prop) {
switch (prop) {
case 'hash':
this[prop] = this.aEl[prop].substr(1);
break;
default:
this[prop] = this.aEl[prop];
}
}, this);
if (this.pathname.indexOf('/') !== 0) {
this.pathname = '/' + this.pathname;
}
this.requestUri = this.pathname + this.search;
};
self.prototype.toObj = function () {
var obj = {};
PROPS.forEach(function (prop) {
obj[prop] = this[prop];
}, this);
obj.requestUri = this.requestUri;
return obj;
};
self.prototype.toString = function () {
return this.href;
};
return self;
})(document);
var URLParser = (function(document) {
var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
var self = function(url) {
this.aEl = document.createElement('a');
this.parse(url);
};
self.prototype.parse = function(url) {
this.aEl.href = url;
if (this.aEl.host == "") {
this.aEl.href = this.aEl.href;
}
PROPS.forEach(function(prop) {
switch (prop) {
case 'hash':
this[prop] = this.aEl[prop].substr(1);
break;
default:
this[prop] = this.aEl[prop];
}
}, this);
if (this.pathname.indexOf('/') !== 0) {
this.pathname = '/' + this.pathname;
}
this.requestUri = this.pathname + this.search;
};
self.prototype.toObj = function() {
var obj = {};
PROPS.forEach(function(prop) {
obj[prop] = this[prop];
}, this);
obj.requestUri = this.requestUri;
return obj;
};
self.prototype.toString = function() {
return this.href;
};
return self;
})(document);
/* Main */
var out = document.getElementById('out');
var urls = [
'https://www.example.org:5887/foo/bar?a=1&b=2#section-1',
'ftp://www.files.com:22/folder?id=7'
];
var parser = new URLParser();
urls.forEach(function(url) {
parser.parse(url);
println(out, JSON.stringify(parser.toObj(), undefined, ' '), 0, '#0000A7');
});
/* Utility functions */
function print(el, text, bgColor, fgColor) {
var span = document.createElement('span');
span.innerHTML = text;
span.style['backgroundColor'] = bgColor || '#FFFFFF';
span.style['color'] = fgColor || '#000000';
el.appendChild(span);
}
function println(el, text, bgColor, fgColor) {
print(el, text, bgColor, fgColor);
el.appendChild(document.createElement('br'));
}
body {
background: #444;
}
span {
background-color: #fff;
border: thin solid black;
display: inline-block;
}
#out {
display: block;
font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
font-size: 12px;
white-space: pre;
}
<div id="out"></div>
{
"protocol": "https:",
"hostname": "www.example.org",
"host": "www.example.org:5887",
"pathname": "/foo/bar",
"port": "5887",
"search": "?a=1&b=2",
"hash": "section-1",
"href": "https://www.example.org:5887/foo/bar?a=1&b=2#section-1",
"requestUri": "/foo/bar?a=1&b=2"
}
{
"protocol": "ftp:",
"hostname": "www.files.com",
"host": "www.files.com:22",
"pathname": "/folder",
"port": "22",
"search": "?id=7",
"hash": "",
"href": "ftp://www.files.com:22/folder?id=7",
"requestUri": "/folder?id=7"
}
function parseUrl(url) {
var m = url.match(/^(([^:\/?#]+:)?(?:\/\/(([^\/?#:]*)(?::([^\/?#:]*))?)))?([^?#]*)(\?[^#]*)?(#.*)?$/),
r = {
hash: m[8] || "", // #asd
host: m[3] || "", // localhost:257
hostname: m[4] || "", // localhost
href: m[0] || "", // http://localhost:257/deploy/?asd=asd#asd
origin: m[1] || "", // http://localhost:257
pathname: m[6] || (m[1] ? "/" : ""), // /deploy/
port: m[5] || "", // 257
protocol: m[2] || "", // http:
search: m[7] || "" // ?asd=asd
};
if (r.protocol.length == 2) {
r.protocol = "file:///" + r.protocol.toUpperCase();
r.origin = r.protocol + "//" + r.host;
}
r.href = r.origin + r.pathname + r.search + r.hash;
return m && r;
};
Он работает как с абсолютными, так и с относительными URL
Вот версия, которую я скопировал из https://gist.github.com/1847816 , но переписан, поэтому ее легче читать и отлаживать. Цель копирования данных привязки в другую переменную с именем «результат» заключается в том, что данные привязки довольно длинные, поэтому копирование ограниченного числа значений в результат поможет упростить результат.
/**
* See: https://gist.github.com/1847816
* Parse a URI, returning an object similar to Location
* Usage: var uri = parseUri("hello?search#hash")
*/
function parseUri(url) {
var result = {};
var anchor = document.createElement('a');
anchor.href = url;
var keys = 'protocol hostname host pathname port search hash href'.split(' ');
for (var keyIndex in keys) {
var currentKey = keys[keyIndex];
result[currentKey] = anchor[currentKey];
}
result.toString = function() { return anchor.href; };
result.requestUri = result.pathname + result.search;
return result;
}
js-uri (доступно в Google Code) принимает строковый URL-адрес и разрешает из него объект URI:
var some_uri = new URI("http://www.example.com/foo/bar");
alert(some_uri.authority); // www.example.com
alert(some_uri); // http://www.example.com/foo/bar
var blah = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full); // http://www.example.com/foo/blah
Просто используйте библиотеку url.js (для web и node.js).
https://github.com/websanova/js-url
url: http://example.com?param=test#param=again
url('?param'); // test
url('#param'); // again
url('protocol'); // http
url('port'); // 80
url('domain'); // example.com
url('tld'); // com
etc...
Современный способ:
new URL("http://example.com/aa/bb/")
Возвращает объект со свойствами hostname
и pathname
, а также несколько других .
Первый аргумент - относительный или абсолютный URL; если он относительный, то вам нужно указать второй аргумент (базовый URL). Например, для URL-адреса относительно текущей страницы:
new URL("/aa/bb/", location)
В дополнение к браузерам этот API также доступен в Node.js , поскольку v7, через require('url').URL
.
new URL('/stuff?foo=bar#baz')
- & gt; SyntaxError: Failed to construct 'URL': Invalid URL
– lakenen
10 June 2014 в 21:25
Как насчет простого регулярного выражения?
url = "http://www.example.com/path/to/somwhere";
urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url);
hostname = urlParts[1]; // www.example.com
path = urlParts[2]; // /path/to/somwhere
Почему бы не использовать его?
$scope.get_location=function(url_str){
var parser = document.createElement('a');
parser.href =url_str;//"http://example.com:3000/pathname/?search=test#hash";
var info={
protocol:parser.protocol,
hostname:parser.hostname, // => "example.com"
port:parser.port, // => "3000"
pathname:parser.pathname, // => "/pathname/"
search:parser.search, // => "?search=test"
hash:parser.hash, // => "#hash"
host:parser.host, // => "example.com:3000"
}
return info;
}
alert( JSON.stringify( $scope.get_location("http://localhost:257/index.php/deploy/?asd=asd#asd"),null,4 ) );
Используйте https://www.npmjs.com/package/uri-parse-lib для этого
var t = parserURI("http://user:pass@example.com:8080/directory/file.ext?query=1&next=4&sed=5#anchor");
pathname
удаляет ведущую косую черту, в то время как другие браузеры этого не делают. Таким образом, вы получите/path
илиpath
, в зависимости от вашего браузера. – TrueWill 9 April 2015 в 19:00