惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - Roland

几个基本的计算机概念 Silverlight 5几个不错的新特性 无光驱采用U盘安装完整版xp javascript 日期格式化(转) .net环境下的javascript引擎汇总 使用ANTLR进行命令行参数解析 使用VSTA定制二次开发IDE(一) 探讨Antlr中文文法与英文文法的差异 .net与java中关于访问性的差异 基础知识之vb.net的拷贝构造函数 垃圾回收浅谈 ASP.NET 页面对象模型[转自Msdnchina] dotnetnuke小结 dotnetnuke中皮肤管理小问题 DNN中令人困惑的用户管理机制 第一次学习dotnetnuke [转帖]怎样成为优秀的软件模型设计者? [转帖]论程序设计方法 让VFP回到旧时代
jQuery URL Parser 帮助
Roland · 2011-07-18 · via 博客园 - Roland

jQuery URL Parser v2.0

A jQuery plugin to parse urls and provide easy access to their attributes (such as the protocol, host, port etc), path segments, querystring parameters, fragment parameters and more.

The core parser functionality is based on the Regex URI parser by Steven Levithan.

Please note that version 2 is not backwards compatible with version 1.x of this plugin. v1.1 is still available for download should you need it for some reason.

This plugin requires jQuery to work. Tested on 1.4 and above but will probably work on older versions, too.

License: http://unlicense.org/ - i.e. do what you want with it :-)

Specifying the URL to parse

There are a few different ways to choose what URL to parse:

var url = $.url(); // parse the current page URL
var url = $.url('http://allmarkedup.com'); // pass in a URI as a string and parse that 
var url = $('#myElement').url(); // extract the URL from the selected element and parse that - will work on any element with a `src`, `href` or `action` attribute.

URL attributes

The .attr() method is used to return information on various parts of the URL. For example:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

The attributes available for querying are:

  • source - the whole url being parsed
  • protocol - eg. http, https, file, etc
  • host - eg. www.mydomain.com, localhost etc
  • port - eg. 80
  • relative - the relative path to the file including the querystring (eg. /folder/dir/index.html?item=value)
  • path - the path to the file (eg. /folder/dir/index.html)
  • directory - the directory part of the path (eg. /folder/dir/)
  • file - the basename of the file eg. index.html
  • query - the entire querystring if it exists, eg. item=value&item2=value2
  • fragment (also available as anchor) - the entire string after the # symbol

There are also a few more obscure ones available too if you want to dig about a bit ;-)

If you don't specify an attribute then this method will return an object literal with all the available attribute key:value pairs in it.

Query string parameters

The .param() method is used to return the values of querystring parameters.

Pass in a string to access that parameter's value:

$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'

If no argument is passed in it will return an object literal containing a key:value map of all the querystring parameters.

$.url('http://allmarkedup.com?sky=blue&grass=green').param(); // returns { 'sky':'blue', 'grass':'green' }

Note that the .param() method will work on both ampersand-split and semicolon-split querystrings.

URL segments

The .segment() method is used to return values of individual segments from the URL's path.

Pass in an integer value to get the value of that segment - note however that the count is not zero-indexed like an array - i.e. .segment(1) returns the firstsegment, not the second one.

You can also pass in negative values, in which case it will count back from the end of the path rather than forwards from the start.

var url = $.url('http://allmarkedup.com/folder/dir/example/index.html');
url.segment(1); // returns 'folder'
url.segment(-2); // returns 'example'

If no argument is passed in it will return an array of all the segments (which will be zero-indexed!).

$.url('http://allmarkedup.com/folder/dir/example/index.html').segment(); // returns ['folder','dir','example','index.html']

Fragment parameters and/or segments

Some sites and apps also use the hash fragment to store querystring-style key value pairs (eg. http://test.com/#sky=blue&grass=green), or slash-delimited paths (eg. http://test.com/#/about/us/).

There are two methods available for extracting information from fragments of these types - .fparam() and .fsegment(), both of which behave indentically to their .param() and .segment() counterparts but act on the fragment rather than the main URL.

$.url('http://test.com/#sky=blue&grass=green').fparam('grass'); // returns 'green'

$.url('http://test.com/#/about/us/').fsegment(1); // returns 'about'

Enabling strict mode

Internally this plugin uses Steven Levithan's excellent Regex URI parser, which has two modes - loose and strict. This plugin uses the loose mode by default (i.e. strict mode set to false), which deviates slightly from the specs but produces more intuitive results. If for some reason you prefer to use the strict parser and so be fully spec-compatible, then you can enable this when calling the plugin as follows:

var url = $.url(true); // parse the current page URL in strict mode
var url = $.url('http://allmarkedup.com',true); // pass in a URI as a string and parse that in strict mode
var url = $('#myElement').url(true); // extract the URL from the selected element and parse that in strict mode

A note on improperly encoded URLs

If you attempt to use this plugin to parse a URL that has an invalid character encoding in it, it will throw a URIError Exception. This will happen if the URL has a percentage sign followed by either a non-numeric character or a numeric value of greater than 80 (i.e. 128 in decimal).

If there is a chance you may end up parsing a badly encoded URL you should probably wrap your calls to this plugin in a try/catch block to prevent this causing unforseen problems.

Thanks to steve78b for pointing this out.