Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Если рисунок не отобразился — прямая ссылка.
var pattern = "^(([^:/\\?#]+):)?(//(([^:/\\?#]*)(?::([^/\\?#]*))?))?([^\\?#]*)(\\?([^#]*))?(#(.*))?$";
var rx = new RegExp(pattern);
var parts = rx.exec(url);
// Пусть текущий URL = 'http://my.site.com/somepath/'
var u = new URL('relative/path/index.html')
u.href // my.site.com/somepath/relative/path/index.html
u.href = '/absolute/path.php?a=8#some-hash'
u.href // my.site.com/absolute/path.php?a=8#some-hash
u.hash // #some-hash
u.protocol = 'https:'
u.href // https://my.site.com/absolute/path.php?a=8#some-hash
u.host = 'another.site.com:8080'
u.href // https://another.site.com:8080/absolute/path.php?a=8#some-hash
u.port // 8080
// и так далее, и тому подобное
* This source code was highlighted with Source Code Highlighter.var u = document.createElement('A');
u.href = 'relative/path/index.html'
u.href // my.site.com/somepath/relative/path/index.html
u.href = '/absolute/path.php?a=8#some-hash'
u.href // my.site.com/absolute/path.php?a=8#some-hash
u.hash // #some-hash
u.protocol = 'https:'
u.href // https://my.site.com/absolute/path.php?a=8#some-hash
u.host = 'another.site.com:8080'
u.href // https://another.site.com:8080/absolute/path.php?a=8#some-hash
u.port // 8080
// и так далее, и тому подобное
* This source code was highlighted with Source Code Highlighter.
this.search = function(val) {
if (typeof val != "undefined") {
search = val;
}
return search;
}
this.search = function(val) {
if (arguments.length) {
search = val;
}
return search;
}
this.href(this.protocol() + '//' + this.host() + this.pathname() + this.search() + this.hash());
this.href = protocol + '//' + host + pathname + search + hash;
if (val.indexOf("/") != 0) { // relative url
var _p = (pathname || window.location.pathname).split("/");
_p[_p.length - 1] = val;
val = _p.join("/");
}
if (val.charAt(0) != '/') { // relative url
val = pathname.replace(/(\/|)$/, '/' + val)
}
// находимся на http://habrahabr.ru/blogs/javascript/65407/
var u = new URL('http://domain.ru');
u.pathname('foo/bar/index.html');
u.href // ожидаете http://domain.ru/foo/bar/index.html получите http://domain.ru/blogs/javascript/65407/foo/bar/index.html
if (arguments.length) { — согласен, так лучше.this.href = protocol + '//' + host + pathname + search + hash; но тут 2 момента:updateURL (из которой вы и привели фрагмент кода) нет никаких сведений ни про какие host, pathname, search и hash, т.к. они находятся внутри замыкания конструктора.this.href = /* всё, что вы написали */ — привдёт к переопределению метода this.href.
String.prototype.parseUrl = function()
{
var matches = this.match(arguments.callee.re);
if ( ! matches ) {
return null;
}
var result = {
'scheme': matches[1] || '',
'subscheme': matches[2] || '',
'user': matches[3] || '',
'pass': matches[4] || '',
'host': matches[5],
'port': matches[6] || '',
'path': matches[7] || '',
'query': matches[8] || '',
'fragment': matches[9] || ''};
return result;
};
String.prototype.parseUrl.re = /^(?:([a-z]+):(?:([a-z]*):)?\/\/)?(?:([^:@]*)(?::([^:@]*))?@)?((?:[a-z0-9_-]+\.)+[a-z]{2,}|localhost|(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])))(?::(\d+))?(?:([^:\?\#]+))?(?:\?([^\#]+))?(?:\#([^\s]+))?$/i;
protocol://user:pass@host:port/path?query#hash (fragment — небольшое разночтение с Вашим hash). Под host подразумеваются доменные имена, IP-адреса и localhost.И забейте вы на эту имитацию protected methods через .call(this), пишите нормально.
* Вот как же я не люблю, когда видимо пришедшие с других языков типа Явы в веб-программирование, пытаются и тут делать монстры-фреймворки на все случаи жизни.
...html&a=1&b=2#/f/o/l/d/e/r/s?c=3&d=4
Конкретно мне надо было распарсить текущий URL и изменить/добавить новый параметр в search, с последующим редиректом.Это конкретно все, что нужно было сделать?
var url_replace = function (new_text,del_old) {
var _stuff,_result,_test_url = window.location.href;
_stuff=((_stuff=test_url.match(/\?([^#]+)/))&&_stuff[1]); // при отсутствии search полУчите null
// теперь работайте с Вашим search
if (del_old&&_stuff) _result=test_url.replace(/\?([^#]+)/,'?'+new_text); //если нужно перезаписать search
else _result=test_url.replace(/(#)|$/,(!_stuff?'?':'&')+new_text+'$1'); // если нужно дополнить search
return _result;
}
* This source code was highlighted with Source Code Highlighter.url_replace('foo=bar') для дополнения или url_replace('foo=bar',1) для замены строки search
Парсим URL